Last active
December 19, 2015 23:09
-
-
Save ayr-ton/6032694 to your computer and use it in GitHub Desktop.
Restify people
This file contains 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
var restify = require('restify') | |
, person = require('save')('people') | |
var server = restify.createServer({ name: 'people-api' }) | |
server.listen(3000, function () { | |
console.log('%s listening at %s', server.name, server.url) | |
}) | |
server | |
.use(restify.fullResponse()) | |
.use(restify.bodyParser()) | |
server.get('/people', function (req, res, next) { | |
person.find({}, function (error, people) { | |
res.send(people) | |
}) | |
}) | |
server.post('/people', function (req, res, next) { | |
if (req.params.name === undefined) { | |
return next(new restify.InvalidArgumentError('Nome precisa ser informado')) | |
} | |
person.create({ name: req.params.name, | |
surname: req.params.surname, | |
position: req.params.position, | |
email: req.params.email }, | |
function (error, newPerson) { | |
if (error) return next(new restify.InvalidArgumentError(JSON.stringify(error.errors))) | |
res.send(201, newPerson) | |
}) | |
}) | |
server.get('/people/:id', function (req, res, next) { | |
person.findOne({ _id: req.params.id }, function (error, aPerson) { | |
if (error) return next(new restify.InvalidArgumentError(JSON.stringify(error.errors))) | |
if (aPerson) { | |
res.send(aPerson) | |
} else { | |
res.send(404) | |
} | |
}) | |
}) | |
server.put('/people/:id', function (req, res, next) { | |
person.update({ _id: req.params.id, | |
name: req.params.name, | |
surname: req.params.surname, | |
position: req.params.position, | |
email: req.params.email }, function (error, aPerson) { | |
if (error) return next(new restify.InvalidArgumentError(JSON.stringify(error.errors))) | |
res.send() | |
}) | |
}) | |
server.del('/people/:id', function (req, res, next) { | |
person.delete(req.params.id, function (error, aPerson) { | |
if (error) return next(new restify.InvalidArgumentError(JSON.stringify(error.errors))) | |
res.send() | |
}) | |
}) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment