From b10bc46c5144020b0d1c72c09299ba2173703383 Mon Sep 17 00:00:00 2001 From: Nathan Hammond Date: Tue, 4 Oct 2016 12:14:11 -0700 Subject: [PATCH] Throw an error when generating an unrecognizable route. --- lib/route-recognizer.js | 16 +++++++++++++--- tests/recognizer-tests.js | 13 +++++++++++++ 2 files changed, 26 insertions(+), 3 deletions(-) diff --git a/lib/route-recognizer.js b/lib/route-recognizer.js index 23979c8..6a8bcaa 100644 --- a/lib/route-recognizer.js +++ b/lib/route-recognizer.js @@ -63,10 +63,15 @@ DynamicSegment.prototype = { }, generate: function(params) { + var value = params[this.name]; + if (value.length === 0) { + throw new Error("You must provide a param `" + this.name + "`."); + } + if (RouteRecognizer.ENCODE_AND_DECODE_PATH_SEGMENTS) { - return encodePathSegment(params[this.name]); + return encodePathSegment(value); } else { - return params[this.name]; + return value; } } }; @@ -82,7 +87,12 @@ StarSegment.prototype = { }, generate: function(params) { - return params[this.name]; + var value = params[this.name]; + if (value.length === 0) { + throw new Error("You must provide a param `" + this.name + "`."); + } + + return value; } }; diff --git a/tests/recognizer-tests.js b/tests/recognizer-tests.js index 612f889..fdcbe84 100644 --- a/tests/recognizer-tests.js +++ b/tests/recognizer-tests.js @@ -909,6 +909,19 @@ globGenerationValues.forEach(function(value) { }); }); +test("throw when generating dynamic routes with empty string", function() { + var router = new RouteRecognizer(); + router.add([{"path":"/posts","handler":"posts"},{"path":"/*secret/create","handler":"create"}], { as: "create"}) + router.add([{"path":"/posts","handler":"posts"},{"path":"/:secret/edit","handler":"edit"}], { as: "edit"}) + + QUnit.throws(function() { + router.generate("create", { secret: "" }); + }, /You must provide a param `secret`./); + QUnit.throws(function() { + router.generate("edit", { secret: "" }); + }, /You must provide a param `secret`./); +}); + test("Parsing and generation results into the same input string", function() { var query = "filter%20data=date"; equal(router.generateQueryString(router.parseQueryString(query)), '?' + query);