Created
August 29, 2012 16:10
-
-
Save eliOcs/3514963 to your computer and use it in GitHub Desktop.
Missing parameter middleware for Restify (Node.js)
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
server.use((function () { | |
var | |
/** | |
* Checks if a request parameter has been defined. | |
*/ | |
contains = function (parameter) { | |
return this.params[parameter] !== undefined; | |
}, | |
/** | |
* Returns a request parameter if its defined otherwise | |
* throws a missing parameter error. | |
*/ | |
get = function (parameter) { | |
if (this.contains(parameter)) { | |
return this.params[parameter]; | |
} else { | |
throw new restify.MissingParameterError(parameter + | |
" is required"); | |
} | |
}; | |
/** | |
* The middleware adds two new functions to the request object. | |
*/ | |
return function (req, res, next) { | |
req.containsParameter = contains; | |
req.getParameter = get; | |
return next(); | |
}; | |
}())); |
sorry guys a stupid question: 'server.use()' define a common handler, wouldn't be more correct to use 'server.pre()' instead? Anyway in both cases i can't throw the MissingParameterError, i just get a 404 error, because the route without a parameter is not registered. i give you an example:
my route:
server.get('/list/:sessionId', listDevices);
if i try with "http://localhost/list" without the sessionId parameter i'd like to throw the MissingParameterError but your handler is not called.. and i get a 404.. i'm confused :-P
thank you guys
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
This doesn't work for me, at least not with restify 2.0.4
I rewrote it so that it would work for me. Thanks for the gist!