Created
May 12, 2014 18:47
-
-
Save typesafe/017b50bb2cd4b37396da to your computer and use it in GitHub Desktop.
resolve parameters in expressjs
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 server = require('./server.js'); | |
var collection = require('./collection.js'); | |
var app = server(); | |
app.put('/items/:id/part', server.resolve(collection), function(req, res){ | |
// no more 404 checking | |
// access resolved item | |
var item = req.resolved; | |
item.part = req.body; | |
// ... | |
}); |
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 express = require('express'); | |
express.resolve = function(collection, param){ | |
return function(req, res, next){ | |
collection.get(req.params[param || 'id']).then(function (item) { | |
if(!item) { | |
res.send(404); | |
return; | |
} | |
req.resolved = item; | |
next(); | |
}); | |
}; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment