udemy-node-todo-app/server/server.js
2017-11-30 23:54:41 -05:00

80 lines
1.9 KiB
JavaScript

const express = require('express')
const _ = require('lodash')
const bodyParser = require('body-parser')
const {ObjectID} = require('mongodb');
var {mongoose} = require('./db/mongoose')
var {User} = require('./models/user')
var {Todo} = require('./models/todo')
var app = express();
const port = process.env.PORT || 8888;
app.use(bodyParser.json());
app.post('/todos', (req, res) => {
var todo = new Todo({
text: req.body.text
});
todo.save().then((doc) => {
return res.send(doc);
}, (e) => {
return res.status(400).send(e);
});
});
app.get('/todos', (req, res) => {
Todo.find().then((todos) => {
return res.send({todos});
}, (e) => {
return res.status(400).send(e);
});
});
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) => {
if(!todo){ return res.status(404).send(); }
return res.send({todo});
}).catch((e) => res.status(400).send())
});
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())
});
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();
});
});
app.listen(port, () => {
console.log(`Started on port ${port}`);
});
module.exports = {app}