96 lines
2.6 KiB
JavaScript
96 lines
2.6 KiB
JavaScript
var UserModel = require('../models/userModel');
|
|
var { MovieModel, SeriesModel } = require('../models/mediaModel');
|
|
|
|
/**
|
|
* mediaController.js
|
|
*
|
|
* @description :: Server-side logic for managing movies and series.
|
|
*/
|
|
module.exports = {
|
|
|
|
/**
|
|
* mediaController.list()
|
|
*/
|
|
list: function (req, res) {
|
|
const MediaModel = req.baseUrl.includes('movies') ? MovieModel : SeriesModel;
|
|
|
|
MediaModel.find({}, { _id: 0, __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, res) {
|
|
const mediaCode = req.body.code;
|
|
const passp = req.body.pass;
|
|
try {
|
|
|
|
const userFound = await UserModel.findOne({ pass: passp });
|
|
if (!userFound) {
|
|
return res.status(404).json({ message: 'Wrong password' });
|
|
}
|
|
|
|
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=${userFound.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, res) {
|
|
var id = req.body.code;
|
|
const passp = req.body.pass;
|
|
|
|
try {
|
|
const userFound = await UserModel.findOne({ pass: passp });
|
|
if (!userFound) {
|
|
return res.status(404).json({ message: 'Wrong password' });
|
|
}
|
|
|
|
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.' });
|
|
}
|
|
},
|
|
};
|