From 240c65226c039c9becaa7fd2335e2699cbe4a63e Mon Sep 17 00:00:00 2001 From: Divyanshu Rathore Date: Mon, 24 Sep 2018 21:07:08 +0530 Subject: [PATCH] Adds update endpoint --- package.json | 1 + server/server.js | 41 +++++++++++++++++++++++++++++++++-------- 2 files changed, 34 insertions(+), 8 deletions(-) diff --git a/package.json b/package.json index fb07d94..4bc2d6f 100644 --- a/package.json +++ b/package.json @@ -17,6 +17,7 @@ "body-parser": "^1.18.3", "expect": "^23.6.0", "express": "^4.16.3", + "lodash": "^4.17.11", "mocha": "^5.2.0", "mongodb": "^3.1.6", "mongoose": "^5.2.17", diff --git a/server/server.js b/server/server.js index b1e32df..9168a6e 100644 --- a/server/server.js +++ b/server/server.js @@ -1,13 +1,14 @@ -let express = require('express'); -let bodyParser = require('body-parser'); -let { ObjectID } = require('mongodb'); +const _ = require('lodash'); +const express = require('express'); +const bodyParser = require('body-parser'); +const { ObjectID } = require('mongodb'); -let { mongoose } = require('./db/mongoose'); -let { Todo } = require('./models/todo'); -let { User } = require('./models/user'); +const { mongoose } = require('./db/mongoose'); +const { Todo } = require('./models/todo'); +const { User } = require('./models/user'); -let app = express(); -let port = process.env.PORT || 3000; +const app = express(); +const port = process.env.PORT || 3000; app.use(bodyParser.json()); @@ -61,6 +62,30 @@ app.delete('/todos/:id', (req, res) => { }).catch((e) => res.status(400).send()); }); +app.put('/todos/:id', (req, res) => { + const id = req.params.id; + const body = _.pick(req.body, ['text', 'completed']); + + if (!ObjectID.isValid(id)) { + return res.status(404).send(); + } + + if (_.isBoolean(body.completed) && body.completed) { + body.completedAt = new Date().getTime(); + } else { + body.completed = false; + body.completedAt = null; + } + + Todo.findByIdAndUpdate(id, {$set: body}, {new: true}).then((todo) => { + if (!todo) { + return res.status(404).send(); + } + + res.send(todo); + }).catch((e) => res.status(400).send()); +}); + app.listen(port, () => { console.log(`Started on port: ${port}`); });