personal_website/controllers/movieController.js
2023-06-26 00:59:11 +02:00

125 lines
3.7 KiB
JavaScript

var MovieModel = require('../models/movieModel');
/**
* movieController.js
*
* @description :: Server-side logic for managing movies.
*/
module.exports = {
/**
* movieController.list()
*/
list: function (req, res) {
MovieModel.find()
.then(movies => {
return res.json(movies);
})
.catch(err => {
return res.status(500).json({
message: 'Error when getting movies.',
error: err
});
});
},
/**
* movieController.create()
*/
create: function (req, res) {
var movie = new MovieModel({
title: req.body.title ? req.body.title : req.body.Title,
released: req.body.released ? req.body.released : req.body.Released,
webImg: req.body.webImg ? req.body.webImg : req.body.WebImg,
genre: req.body.genre ? req.body.genre : req.body.Genre,
code: req.body.code ? req.body.code : req.body.Code
});
MovieModel.findOne({ code: movie.code })
.then(movieFound => {
if (movieFound) {
return res.status(409).json({
message: 'Movie already exists'
});
}
else
{
movie.save()
.then(savedMovie => {
// Handle successful save operation
return res.json(savedMovie);
})
.catch(err => {
return res.status(500).json({
message: 'Error when creating movie',
error: err
});
});
}
})
.catch(err => {
return res.status(500).json({
message: 'Error when getting movie',
error: err
})
});
},
/**
* movieController.update()
*/
update: function (req, res) {
var id = req.params.id;
MovieModel.findOne({ _id: id })
.then(movie => {
if (!movie) {
return res.status(404).json({
message: 'No such movie'
});
}
movie.title = req.body.title ? req.body.title : movie.title;
movie.released = req.body.released ? req.body.released : movie.released;
movie.webImg = req.body.webImg ? req.body.webImg : movie.webImg;
movie.genre = req.body.genre ? req.body.genre : movie.genre;
movie.code = req.body.code ? req.body.code : movie.code;
return movie.save();
})
.then(updatedMovie => {
return res.json(updatedMovie);
})
.catch(err => {
return res.status(500).json({
message: 'Error when updating movie.',
error: err
});
});
},
/**
* movieController.remove()
*/
remove: function (req, res) {
var id = req.params.id;
console.log(id);
MovieModel.findOneAndDelete({ code: id })
.then(movie => {
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.',
error: err
});
});
},
};