Skip to content

Commit

Permalink
feature(templates): adding strict mode for placeholder replacement (#331
Browse files Browse the repository at this point in the history
)

When activated, strict mode makes URITemplate throw instead of
silently replacing missing values by empty strings.
  • Loading branch information
tobie authored and rodneyrehm committed Mar 6, 2017
1 parent d6691b3 commit c70874e
Show file tree
Hide file tree
Showing 3 changed files with 17 additions and 3 deletions.
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

0 comments on commit c70874e

Please sign in to comment.