From 2f22fb6be8829dd53fe49eb44c569d4f5500e8e9 Mon Sep 17 00:00:00 2001 From: JayWll Date: Sun, 23 Feb 2020 17:34:28 -0700 Subject: [PATCH] Video 99: Resource Updating Endpoints: Part II --- task-manager/src/index.js | 22 ++++++++++++++++++++++ 1 file changed, 22 insertions(+) diff --git a/task-manager/src/index.js b/task-manager/src/index.js index 638a0fc..9e6c881 100644 --- a/task-manager/src/index.js +++ b/task-manager/src/index.js @@ -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, () => { console.log('Server is up on port ' + port) })