From 4b1ad55daaedaef889f9c82c8c89a856feff25a7 Mon Sep 17 00:00:00 2001 From: JayWll Date: Sun, 23 Feb 2020 17:25:21 -0700 Subject: [PATCH] Video 98: Resource Updating Endpoints: Part I --- 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 1cacc3e..638a0fc 100644 --- a/task-manager/src/index.js +++ b/task-manager/src/index.js @@ -44,6 +44,28 @@ app.get('/users/:id', async (req, res) => { } }) +app.patch('/users/:id', async (req, res) => { + const updates = Object.keys(req.body) + const allowedUpdates = ['name', 'email', 'password', 'age'] + const isValidOperation = updates.every((update) => allowedUpdates.includes(update)) + + if (!isValidOperation) { + return res.status(400).send({ error: 'Invalid updates!' }) + } + + try { + const user = await User.findByIdAndUpdate(req.params.id, req.body, { new: true, runValidators: true }) + + if (!user) { + return res.status(404).send() + } + + res.send(user) + } catch (e) { + res.status(400).send(e) + } +}) + app.post('/tasks', async (req, res) => { const task = new Task(req.body)