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)
}
})
router.put('/movies/:id', Controller.UpdateMoviceName). - hotcakedev