From 3a35b26cf5845e8aa097f5541eb03cf2ad23bb36 Mon Sep 17 00:00:00 2001 From: Fabian Jakobs Date: Mon, 21 Dec 2015 14:28:03 +0000 Subject: [PATCH] treat optional arguments with a value of null like undefined values --- node_modules/frontdoor/lib/route.js | 21 ++++++++++++---- node_modules/frontdoor/lib/route_test.js | 32 ++++++++++++++++++++++++ 2 files changed, 48 insertions(+), 5 deletions(-) diff --git a/node_modules/frontdoor/lib/route.js b/node_modules/frontdoor/lib/route.js index a4f3eeee..9797883c 100644 --- a/node_modules/frontdoor/lib/route.js +++ b/node_modules/frontdoor/lib/route.js @@ -195,19 +195,25 @@ module.exports = function Route(route, options, handler, types) { var type = param.type; var value = EMPTY; var isValid = true; - switch(param.source) { + switch (param.source) { case "body": if (param.optional && !(key in body)) break; value = body[key]; // body is already JSON parsed - if (param.optional && value == null) + if (param.optional && value == null) { + value = EMPTY; break; + } + isValid = type.check(value); break; + case "query": - if (param.optional && query[key] == null) + if (param.optional && query[key] == null) { + value = EMPTY; break; + } try { value = type.parse(query[key]); @@ -216,13 +222,19 @@ module.exports = function Route(route, options, handler, types) { } isValid = isValid === false ? false : type.check(value); break; + case "url": - if (param.optional && urlParams[key] == null) + if (param.optional && urlParams[key] == null) { + value = EMPTY; break; + } value = urlParams[key]; // is already parsed and checked isValid = true; break; + + default: + throw new Error("Invalid source: " + params.source); } if (!isValid) { @@ -238,7 +250,6 @@ module.exports = function Route(route, options, handler, types) { req.params[key] = value; else if ("default" in param) req.params[key] = param.default; - } } } diff --git a/node_modules/frontdoor/lib/route_test.js b/node_modules/frontdoor/lib/route_test.js index d1a1bacd..da1da6a5 100644 --- a/node_modules/frontdoor/lib/route_test.js +++ b/node_modules/frontdoor/lib/route_test.js @@ -164,6 +164,38 @@ module.exports = { }); }, + "test router: decode parameter in body with defaults": function(next) { + var route = new Route("/user", { + params: { + scm: { + type: /^(git|hg)?$/, + optional: true, + default: "git", + source: "body" + } + } + }, sinon.stub()); + + var req = { + match: "match", + parsedUrl: { query: "" }, + body: { } + }; + var res = {}; + + route.decodeParams(req, res, function(err, result) { + assert.equal(err, null); + assert.equal(req.params.scm, "git"); + + req.body.scm = null; // should be treated the same as undefined + route.decodeParams(req, res, function(err, result) { + assert.equal(err, null); + assert.equal(req.params.scm, "git"); + next(); + }); + }); + }, + "test router: optional number argument can be falsy": function(next) { var route = new Route("/user", { params: {