Allow optional parameters to be falsy

pull/85/head
Lennart Kats 2015-04-29 11:32:32 +02:00
rodzic 340a218b6d
commit 58afdf088c
2 zmienionych plików z 68 dodań i 4 usunięć

12
node_modules/frontdoor/lib/route.js wygenerowano vendored
Wyświetl plik

@ -137,6 +137,10 @@ module.exports = function Route(route, options, handler, types) {
var key = keys[i];
var param = params[key];
var type = param.type;
if (param.optional && value == null) {
match[key] = value;
continue;
}
try {
value = type.parse(value);
} catch (e) {
@ -157,7 +161,7 @@ module.exports = function Route(route, options, handler, types) {
* the decoded and validated parameters are stored in `req.params`
* otherwhise an error is returned.
*/
function decodeParams(req, res, next) {
var decodeParams = this.decodeParams = function(req, res, next) {
var urlParams = req.match;
if (!urlParams) return;
@ -197,10 +201,12 @@ module.exports = function Route(route, options, handler, types) {
break;
value = body[key]; // body is already JSON parsed
if (param.optional && value == null)
break;
isValid = type.check(value);
break;
case "query":
if (param.optional && !(key in query))
if (param.optional && query[key] == null)
break;
try {
@ -211,7 +217,7 @@ module.exports = function Route(route, options, handler, types) {
isValid = isValid === false ? false : type.check(value);
break;
case "url":
if (param.optional && !(key in urlParams))
if (param.optional && urlParams[key] == null)
break;
value = urlParams[key]; // is already parsed and checked

60
node_modules/frontdoor/lib/route_test.js wygenerowano vendored
Wyświetl plik

@ -133,7 +133,65 @@ module.exports = {
assert.ok(!route.match(req, "/ts/353676299181"));
assert.ok(!route.match(req, "/ts/abc"));
}
},
"test router: decode parameter in body": function(next) {
var route = new Route("/user", {
params: {
id: {
type: "int",
optional: true,
source: "body"
}
}
}, sinon.stub());
var req = {
match: "match",
parsedUrl: {
query: ""
},
body: { id: 15 }
};
var res = {};
// Note: usually optionals would say 'source: "body",'
// but this should work
route.decodeParams(req, res, function(err, result) {
assert.equal(err, null);
assert.equal(req.params.id, 15);
next();
});
},
"test router: optional number argument can be falsy": function(next) {
var route = new Route("/user", {
params: {
id: {
type: "int",
optional: true,
source: "body"
}
}
}, sinon.stub());
var req = {
match: "match",
parsedUrl: {
query: ""
},
body: { id: null }
};
var res = {};
// Note: usually optionals would say 'source: "body",'
// but this should work
route.decodeParams(req, res, function(err, result) {
assert.equal(err, null);
assert.equal(req.params.id, null);
next();
});
},
};
!module.parent && require("asyncjs").test.testcase(module.exports).exec();