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#expand. #331

Merged
merged 1 commit into from Mar 6, 2017
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
9 changes: 6 additions & 3 deletions src/URITemplate.js
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
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
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