personal_website/controllers/mediaController.ts
2024-07-16 19:04:16 +02:00

92 lines
2.4 KiB
TypeScript

import { type Request, type Response } from "express";
import UserModel, { values } from '../models/userModel';
import { MovieModel, SeriesModel } from '../models/mediaModel';
/**
* mediaController.js
*
* @description :: Server-side logic for managing movies and series.
*/
export default {
/**
* mediaController.list()
*/
list: function (req: Request, res: Response) {
const MediaModel = req.baseUrl.includes('movies') ? MovieModel : SeriesModel;
MediaModel.find({}, { __v: 0 })
.then(media => {
return res.json(media);
})
.catch(err => {
return res.status(500).json({
message: 'Error when getting media.',
error: err
});
});
},
/**
* mediaController.create()
*/
create: async function (req: Request, res: Response) {
const mediaCode = req.body.code;
const omdb_key = await UserModel.getValue(values.omdb_key);
if (!omdb_key) {
return res.status(500).json({ message: 'Error when creating media' });
}
try {
const MediaModel = req.baseUrl.includes('movies') ? MovieModel : SeriesModel;
const mediaFound = await MediaModel.findOne({ code: mediaCode });
if (mediaFound) {
return res.status(409).json({ message: 'Media already exists' });
}
const uri = `http://www.omdbapi.com/?i=${mediaCode}&apikey=${omdb_key}`;
const mJson = await fetch(uri);
const mData = await mJson.json();
if (mData.Response == 'False') {
return res.status(404).json({ message: 'wrong code' });
}
const media = new MediaModel({
code: mediaCode,
title: mData.Title,
released: mData.Released,
webImg: mData.Poster,
});
const savedMedia = await media.save();
return res.status(201).json(media);
} catch (err) {
return res.status(500).json({ message: 'Error when creating media' });
}
},
/**
* mediaController.delete()
*/
remove: async function (req: Request, res: Response) {
const id = req.body.code;
try {
const MediaModel = req.baseUrl.includes('movies') ? MovieModel : SeriesModel;
const media = await MediaModel.findOneAndDelete({ code: id });
if (!media) {
return res.status(404).json({ message: 'No such media' });
}
return res.status(204).json();
}
catch (err) {
return res.status(500).json({ message: 'Error when deleting the media.' });
}
},
};