Created
August 18, 2011 19:21
-
-
Save hugdubois/1154913 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 mongoose = require('mongoose') | |
, Schema = mongoose.Schema; | |
function NotFound(msg){ | |
this.name = 'NotFound'; | |
Error.call(this, msg); | |
Error.captureStackTrace(this, arguments.callee); | |
} | |
NotFound.prototype.__proto__ = Error.prototype; | |
mongoose.model('User', new Schema({ | |
"name": {type: String, required: true, index: true} | |
})); | |
mongoose.connect('mongodb://localhost/foo-db', function(err) {if (err) throw err;}); | |
var app = require('express').createServer(); | |
app.error(function(err, req, res, next){ | |
if (err instanceof NotFound) { | |
res.send({code:404, message: err.message||'Not Found'}, 404); | |
} else { | |
res.send({code:500, message: err.messgae||'Internal error', stack:err.stack.split('\n')}, 500); | |
} | |
}); | |
var findUserByIdAndAttachToRequest = function(prop) { | |
return function(req, res, next, id) { | |
console.log('Search user #'+id+' and put in req.'+prop); | |
mongoose.model('User').findById(id, function(err, user) { | |
if (err) return next(err); | |
if (!user) return next(new NotFound('User not found')); | |
req[prop] = user; | |
next(); | |
}); | |
}; | |
}; | |
app.param('from_id', findUserByIdAndAttachToRequest('_fromUser')); | |
app.param('to_id', findUserByIdAndAttachToRequest('_toUser')); | |
app.get('/users/:from_id/friend/:to_id', function(req, res, next) { | |
res.send({formUser:req._fromUser.name, toUser:req._toUser.name}); | |
}); | |
app.listen(3000); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment