Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add a strict mode option to URITemplate. #330

Closed
wants to merge 10 commits into from
9 changes: 6 additions & 3 deletions src/URITemplate.js
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand All @@ -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)
Expand Down Expand Up @@ -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) {
Expand All @@ -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 */
}

Expand Down
6 changes: 6 additions & 0 deletions test/test_template.js
Original file line number Diff line number Diff line change
Expand Up @@ -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.');
});

})();
5 changes: 5 additions & 0 deletions uri-template.html
Original file line number Diff line number Diff line change
Expand Up @@ -107,6 +107,11 @@ <h2>Using URI Templates</h2>
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"
</pre>


Expand Down