Minimal Port of Express.js Route Param Pre-conditions #93

Merged
merged 1 commit into from Mar 5, 2012
View
27 lib/server.js
@@ -196,7 +196,7 @@ function Server(options) {
str += self.address().port;
return str;
});
-
+
this.__defineGetter__('responseTimeHeader', function () {
return options.responseTimeHeader || 'X-Response-Time';
});
@@ -536,3 +536,28 @@ Server.prototype._findRoute = function _findRoute(req, res) {
return route || false;
};
+
+/**
+ * Minimal port of the functionality offered by Express.js Route Param Pre-conditions
+ * @link http://expressjs.com/guide.html#route-param%20pre-conditions
+ *
+ * This basically piggy-backs on the `server.use` method. It attaches a
+ * new middleware function that only fires if the specified parameter exists
+ * in req.params
+ *
+ * Exposes an API:
+ * server.param("user", function (req, res, next) {
+ * // load the user's information here, always making sure to call next()
+ * });
+ *
+ * @param {String} The name of the URL param to respond to
+ * @param {Function} The middleware function to execute
+ */
+Server.prototype.param = function (name, fn) {
+ this.use(function (req, res, next) {
+ if (req.params && req.params[name]) {
+ return fn.apply(this, arguments);
+ }
+ next();
+ });
+};