Reputation: 1
Im looking for some help to resolve an exercise.. Im learning about the PUT method and how can i change a movie object... I need to use a forEach, an IF, and a req.body.
The initial code is:
let movies = [
{
id: 1,
title: 'Spider-Man',
duration: 129,
genre: 'Adventure'
},
{
id: 2,
title: 'Toy Story 4',
duration: 100,
genre: 'Animation'
},
{
id: 3,
title: 'X-Men',
duration: 113,
genre: 'Action'
}
];
const express = require('express');
const router = express.Router();
Im adding a
router.put('/movies/:id', function(req, res){ }
but i don't know what to put inside the {}
Upvotes: 0
Views: 238
Reputation: 46610
i don't know what to put inside the {}
Code that contains logic to update the array.
For example:
router.put('/movies/:id', function(req, res, next) {
try {
// get id from :id, parse it to an int
let id = parseInt(req.params.id, 10) || false
// validate
if (!id) {
let err = new Error('Invalid movie id')
err.status = 422
throw err
}
// find the movie
let index = movies.findIndex(v => v.id === id)
if (index === -1) {
let err = new Error('Movie not found')
err.status = 404
throw err
}
// seems good, now lets validate body
let errors = {}
// id
if (!req.body.id) {
errors.id = 'Id is a required field'
} else if (isNaN(req.body.id)) {
errors.id = 'Id is invalid, number required'
}
//title
if (!req.body.title) {
errors.title = 'Title is a required field'
} else if (req.body.title.length <= 1) {
errors.title = 'Title too short, enter greater than 1 character'
} else if (req.body.title.length >= 255) {
errors.title = 'Title too long, enter less than 255 characters'
}
// duration
if (typeof req.body.duration === 'undefined') {
errors.duration = 'Duration is a required field'
} else if (req.body.duration < 0) {
errors.duration = 'Duration cannot be negative, enter greater than 0 minute'
} else if (req.body.duration >= 1440) {
errors.duration = 'Duration too long, enter less than than 1440 minutes (1 day)'
}
//genre
if (!req.body.genre) {
errors.genre = 'Genre is a required field'
}
// has errors
if (Object.keys(errors).length) {
let err = new Error('Invlid inputs')
err.status = 422
err.errors = errors
throw err
}
//
movies[index] = {
id: req.body.id,
title: req.body.title,
duration: req.body.duration,
genre: req.body.genre
}
// send success response
res.json({
status: 200
})
} catch (err) {
next(err)
}
})
Error handler to catch what was thrown from middleware
app.use(function(error, req, res, next) {
// set response header
res.status(error.status || 500)
// is xhr/ajax
if (req.xhr) {
res.json(error)
}
// not ajax
else {
res.render('error', error)
}
})
Upvotes: 1