udemy-node-todo-app/server/server.js

80 lines
1.9 KiB
JavaScript
Raw Normal View History

2017-12-01 04:54:41 +00:00
const express = require('express')
const _ = require('lodash')
const bodyParser = require('body-parser')
2017-12-01 03:18:17 +00:00
const {ObjectID} = require('mongodb');
2017-11-30 03:52:44 +00:00
var {mongoose} = require('./db/mongoose')
var {User} = require('./models/user')
var {Todo} = require('./models/todo')
var app = express();
2017-12-01 03:33:22 +00:00
const port = process.env.PORT || 8888;
2017-11-30 03:52:44 +00:00
app.use(bodyParser.json());
app.post('/todos', (req, res) => {
var todo = new Todo({
text: req.body.text
});
todo.save().then((doc) => {
2017-11-30 04:15:25 +00:00
return res.send(doc);
2017-11-30 03:52:44 +00:00
}, (e) => {
2017-11-30 04:15:25 +00:00
return res.status(400).send(e);
});
});
2017-11-30 03:52:44 +00:00
2017-11-30 04:32:28 +00:00
app.get('/todos', (req, res) => {
2017-12-01 03:18:17 +00:00
Todo.find().then((todos) => {
2017-11-30 04:32:28 +00:00
return res.send({todos});
}, (e) => {
return res.status(400).send(e);
});
});
2017-12-01 03:18:17 +00:00
app.get('/todos/:id', (req, res) => {
var id = req.params.id;
if (!ObjectID.isValid(id)){
return res.status(404).send();
}
Todo.findById(req.params.id).then((todo) => {
2017-12-01 04:29:42 +00:00
if(!todo){ return res.status(404).send(); }
2017-12-01 03:18:17 +00:00
return res.send({todo});
}).catch((e) => res.status(400).send())
});
2017-12-01 04:29:42 +00:00
app.delete('/todos/:id', (req, res) => {
var id = req.params.id;
if (!ObjectID.isValid(id)){ return res.status(404).send(); }
Todo.findByIdAndRemove(id).then((todo) => {
if(!todo){ return res.status(404).send(); }
return res.send({todo});
}).catch((e) => res.status(400).send())
});
2017-11-30 04:32:28 +00:00
2017-12-01 04:54:41 +00:00
app.patch('/todos/:id', (req, res) => {
var id = req.params.id;
var 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.completedAt = null;
body.completed = false;
}
Todo.findByIdAndUpdate(id, { $set: body, }, { new: true }).then((todo) => {
if(!todo){ return res.status(404).send(); }
return res.send({todo});
}).catch((e) => {
res.status(400).send();
});
});
2017-12-01 03:33:22 +00:00
app.listen(port, () => {
console.log(`Started on port ${port}`);
2017-11-30 03:52:44 +00:00
});
2017-11-30 04:15:25 +00:00
module.exports = {app}