Created
December 28, 2017 21:47
-
-
Save aramkoukia/8797a52c08b2ef5c6a4016e2cb142543 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const ToDo = require('./todo.model'); | |
const ReadPreference = require('mongodb').ReadPreference; | |
require('./mongo').connect(); | |
function getToDoes(req, res) { | |
const docquery = ToDo.find({}).read(ReadPreference.NEAREST); | |
docquery | |
.exec() | |
.then(todoes => res.status(200).json(todoes)) | |
.catch(error => res.status(500).send(error)); | |
} | |
function postToDo(req, res) { | |
const originalToDo = { | |
id: req.body.todo.id, | |
name: req.body.todo.name, | |
saying: req.body.todo.saying | |
}; | |
const todo = new ToDo(originalToDo); | |
todo.save(error => { | |
if (checkServerError(res, error)) return; | |
res.status(201).json(todo); | |
console.log('ToDo created successfully!'); | |
}); | |
} | |
function putToDo(req, res) { | |
const updatedToDo = { | |
id: parseInt(req.params.id, 10), | |
name: req.body.todo.name, | |
saying: req.body.todo.saying | |
}; | |
ToDo.findOneAndUpdate( | |
{ id: updatedToDo.id }, | |
{ $set: updatedToDo }, | |
{ upsert: true, new: true }, | |
(error, doc) => { | |
if (checkServerError(res, error)) return; | |
res.status(200).json(doc); | |
console.log('ToDo updated successfully!'); | |
} | |
); | |
} | |
function deleteToDo(req, res) { | |
const id = parseInt(req.params.id, 10); | |
ToDo.findOneAndRemove({ id: id }) | |
.then(todo => { | |
if (!checkFound(res, todo)) return; | |
res.status(200).json(todo); | |
console.log('ToDo deleted successfully!'); | |
}) | |
.catch(error => { | |
if (checkServerError(res, error)) return; | |
}); | |
} | |
function checkServerError(res, error) { | |
if (error) { | |
res.status(500).send(error); | |
return error; | |
} | |
} | |
function checkFound(res, todo) { | |
if (!todo) { | |
res.status(404).send('ToDo not found.'); | |
return; | |
} | |
return todo; | |
} | |
module.exports = { | |
getToDoes, | |
postToDo, | |
putToDo, | |
deleteToDo | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment