1
0

Video 99: Resource Updating Endpoints: Part II

This commit is contained in:
JayWll 2020-02-23 17:34:28 -07:00
parent 4b1ad55daa
commit 2f22fb6be8

View File

@ -102,6 +102,28 @@ app.get('/tasks/:id', async (req, res) => {
} }
}) })
app.patch('/tasks/:id', async (req, res) => {
const updates = Object.keys(req.body)
const allowedUpdates = ['description', 'completed']
const isValidOperation = updates.every((update) => allowedUpdates.includes(update))
if (!isValidOperation) {
return res.status(400).send({ error: 'Invalid updates!' })
}
try {
const task = await Task.findByIdAndUpdate(req.params.id, req.body, { new: true, runValidators: true })
if (!task) {
return res.status(404).send()
}
res.send(task)
} catch (e) {
res.status(400).send(e)
}
})
app.listen(port, () => { app.listen(port, () => {
console.log('Server is up on port ' + port) console.log('Server is up on port ' + port)
}) })