const express = require('express');
const router = express.Router();
var movieGenres = [
{ id: 1, name: 'Sci-Fi' },
{ id: 2, name: 'Romantic' },
{ id: 3, name: 'Drama' },
{ id: 4, name: 'Action' },
{ id: 5, name: 'Family' }
];
// Get All Movie Genre
router.get('/', (req, res) => {
res.send(movieGenres);
});
// Search and Get the movie genre by ID
router.get('/:id', (req, res) => {
const genre = movieGenres.find(genre => genre.id === parseInt(req.params.id));
if(!genre) return res.status(404).send('Movie Genre with that ID was NOT FOUND');
res.send(genre);
});
// Inserting new Movie Generes into the Array
router.post('/', (req, res)=>{
const schema = {
name: Joi.string().min(3).required()
};
const result = Joi.validate(req.body, schema);
if(result.error){
res.send(result.error.details[0].message)
return;
}
var movieGenre = {
id: movieGenres.length+1,
name: req.body.name
};
movieGenres.push(movieGenre);
res.send(movieGenre);
});
// Updating value of Movie Genre
router.put('/:id', (req, res)=>{
const genre = movieGenres.find(genre => genre.id === parseInt(req.params.id));
if(!genre) return res.status(404).send('Movie Genre with that ID was NOT FOUND');
const schema = {
name: Joi.string().min(3).required()
};
const result = Joi.validate(req.body, schema);
if(result.error){
res.send(result.error.details[0].message)
return;
}
genre.name= req.body.name;
res.send(genre);
});
// Delete movie genre from the array
router.delete('/:id', (req, res)=>{
const genre = movieGenres.find(genre => genre.id === parseInt(req.params.id));
if(!genre) return res.status(404).send('Movie Genre with that ID was NOT FOUND');
const index = movieGenres.indexOf(genre);
movieGenres.splice(index, 1);
res.send(genre);
});
module.exports = router;