personal_website/controllers/movieController.js
2023-07-12 17:47:32 +02:00

95 lines
2.5 KiB
JavaScript

var MovieModel = require('../models/movieModel');
var UserModel = require('../models/userModel');
/**
* movieController.js
*
* @description :: Server-side logic for managing movies.
*/
module.exports = {
/**
* movieController.list()
*/
list: function (req, res) {
MovieModel.find({}, {_id: 0, __v: 0})
.then(movies => {
return res.json(movies);
})
.catch(err => {
return res.status(500).json({
message: 'Error when getting movies.',
error: err
});
});
},
/**
* movieController.create()
*/
create: async function (req, res) {
const movieCode = 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 movieFound = await MovieModel.findOne({ code: movieCode });
if (movieFound) {
return res.status(409).json({ message: 'Movie already exists' });
}
const uri = `http://www.omdbapi.com/?i=${movieCode}&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 movie = new MovieModel({
code: movieCode,
title: mData.Title,
released: mData.Released,
webImg: mData.Poster,
genre: mData.Genre
});
const savedMovie = await movie.save();
return res.status(201).json(movie);
} catch (err) {
return res.status(500).json({ message: 'Error when creating movie' });
}
},
/**
* movieController.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 movie = await MovieModel.findOneAndDelete({ code: id });
if (!movie) {
return res.status(404).json({ message: 'No such movie' });
}
return res.status(204).json();
}
catch(err)
{
return res.status(500).json({ message: 'Error when deleting the movie.' });
}
},
};