personal_website/controllers/mediaController.ts
2024-07-16 20:18:46 +02:00

91 lines
2.5 KiB
TypeScript

import { type Request, type Response } from "express";
import UserModel, { values } from '../models/userModel';
import MediaModel, { Table } 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 mediaTable = req.baseUrl.includes('movies') ? Table.movies : Table.series;
MediaModel.find(mediaTable)
.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 mediaTable = req.baseUrl.includes('movies') ? Table.movies : Table.series;
const mediaFound = await MediaModel.findOne(mediaTable, 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 = {
code: mediaCode,
title: mData.Title,
released: mData.Released,
webImg: mData.Poster,
};
const savedMedia = await MediaModel.save(mediaTable, mediaCode, mData.Title, mData.Released, mData.Poster);
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 code = req.body.code;
try {
const mediaTable = req.baseUrl.includes('movies') ? Table.movies : Table.series;
const media = await MediaModel.findOneAndDelete(mediaTable, code);
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.' });
}
},
};