-
-
Save simondahla/6644168 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
var restify = require('restify'), | |
mongoose = require('mongoose'); | |
var server = restify.createServer({ | |
name: 'mongo-api' | |
}) | |
server.listen(7000, function () { | |
console.log('%s listening at %s', server.name, server.url) | |
}) | |
db = mongoose.connect("mongodb://localhost/example-api"); | |
var Schema = mongoose.Schema, | |
ObjectId = Schema.ObjectID; | |
var User = new Schema({ | |
email: { | |
type: String, | |
required: true, | |
trim: true | |
}, | |
fname: { | |
type: String, | |
required: false, | |
trim: true | |
}, | |
lname: { | |
type: String, | |
required: false, | |
trim: true | |
}, | |
}); | |
var User = mongoose.model('User', User); | |
server | |
.use(restify.fullResponse()) | |
.use(restify.bodyParser()) | |
server.get('/user', function (req, res, next) { | |
User.find({}, function (error, users) { | |
res.send(users) | |
}) | |
}) | |
server.post('/user', function (req, res, next) { | |
if (req.params.email === undefined) { | |
return next(new restify.InvalidArgumentError('Email must be supplied')) | |
} | |
var userData = { | |
email: req.params.email, | |
fname: req.params.fname, | |
lname: req.params.lname | |
} | |
var user = new User(userData); | |
user.save(function (error, data) { | |
if (error) { | |
return next(new restify.InvalidArgumentError(JSON.stringify(error.errors))) | |
} | |
else { | |
res.json(data); | |
} | |
res.send(201, user) | |
}) | |
}) | |
server.get('/user/:id', function (req, res, next) { | |
User.findOne({ | |
_id: req.params.id | |
}, function (error, user) { | |
if (error) return next(new restify.InvalidArgumentError(JSON.stringify(error.errors))) | |
if (user) { | |
res.send(user) | |
} | |
else { | |
res.send(404) | |
} | |
}) | |
}) | |
server.put('/user/:id', function (req, res, next) { | |
if (req.params.email === undefined) { | |
return next(new restify.InvalidArgumentError('Email must be supplied')) | |
} | |
var userData = { | |
email: req.params.email, | |
fname: req.params.fname, | |
lname: req.params.lname | |
} | |
User.update({ | |
_id: req.params.id | |
}, userData, { | |
multi: false | |
}, function (error, user) { | |
if (error) return next(new restify.InvalidArgumentError(JSON.stringify(error.errors))) | |
res.send() | |
}) | |
}) | |
server.del('/user/:id', function (req, res, next) { | |
User.remove({ | |
_id: req.params.id | |
}, function (error, user) { | |
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