From 97d09c35846471c2d4fcf6e9ef58f41992b68080 Mon Sep 17 00:00:00 2001 From: Tobie Langel Date: Mon, 6 Mar 2017 10:17:17 +0100 Subject: [PATCH] Add a strict mode option to URITemplate. When activated, strict mode makes URITemplate throw instead of silently replacing missing values by empty strings. --- src/URITemplate.js | 9 ++++++--- test/test_template.js | 6 ++++++ uri-template.html | 5 +++++ 3 files changed, 17 insertions(+), 3 deletions(-) diff --git a/src/URITemplate.js b/src/URITemplate.js index 3272785f..93fd3dea 100644 --- a/src/URITemplate.js +++ b/src/URITemplate.js @@ -140,7 +140,7 @@ URITemplate.LITERAL_PATTERN = /[<>{}"`^| \\]/; // expand parsed expression (expression, not template!) - URITemplate.expand = function(expression, data) { + URITemplate.expand = function(expression, data, opts) { // container for defined options for the given operator var options = operators[expression.operator]; // expansion type (include keys or not) @@ -154,6 +154,9 @@ for (i = 0; (variable = variables[i]); i++) { // fetch simplified data source d = data.get(variable.name); + if (d.type === 0 && opts && opts.strict) { + throw new Error('Missing expansion value for variable "' + variable.name + '"'); + } if (!d.val.length) { if (d.type) { // empty variables (empty string) @@ -320,7 +323,7 @@ }; // expand template through given data map - p.expand = function(data) { + p.expand = function(data, opts) { var result = ''; if (!this.parts || !this.parts.length) { @@ -340,7 +343,7 @@ // literal string ? this.parts[i] // expression - : URITemplate.expand(this.parts[i], data); + : URITemplate.expand(this.parts[i], data, opts); /*jshint laxbreak: false */ } diff --git a/test/test_template.js b/test/test_template.js index 16db0179..b2b5f037 100644 --- a/test/test_template.js +++ b/test/test_template.js @@ -408,4 +408,10 @@ }, Error, 'Failing invalid literal'); }); + test('Strict mode', function () { + raises(function() { + new URITemplate("/{foo}/bar").expand({ foobar: 123 }, { strict: true }); + }, Error, 'Missing expansion value for variable in strict mode.'); + }); + })(); diff --git a/uri-template.html b/uri-template.html index d49065c9..c9407629 100644 --- a/uri-template.html +++ b/uri-template.html @@ -107,6 +107,11 @@

Using URI Templates

template.expand({file : function(key) { return "hello world.html"; }}); + +// Using strict mode +var template = new URITemplate("http://example.org/{file}"); +var result = template.expand({filename: "hello world.html"}, { strict: true }); +// Uncaught Error: Missing expansion value for variable "file"