UNPKG

1.27 kBJavaScriptView Raw
1'use strict';
2
3var _ = require('lodash');
4
5// Given a url extracts any named template parameters beginning with a colon.
6//
7// E.g. /foo/:bar/baz/:quux ---> [ 'bar', 'quux' ]
8//
9// - @param {String} url - the url to parse
10// - @return {Array} an array of named parameters
11function templateParams(url) {
12 return url.match(/:([^/]+)/g);
13}
14
15// Given a url and some parameters replaces all named parameters with those
16// supplied.
17//
18// - @param {String} url - the url to be modified
19// - @param {Object} params - a hash of parameters to be put in the URL
20// - @return {String} The url with the parameters replaced
21function template(url, params) {
22 var templated = url;
23 var keys = _.keys(params);
24 var loweredKeys = _.map(keys, function (key) {
25 return key.toLowerCase();
26 });
27 var keyLookup = _.zipObject(loweredKeys, keys);
28
29 _.each(templateParams(url), function replaceParam(param) {
30 var normalisedParam = param.toLowerCase().substr(1);
31
32 if (!keyLookup[normalisedParam]) {
33 throw new Error('Missing ' + normalisedParam);
34 }
35
36 templated = templated.replace(param,
37 params[keyLookup[normalisedParam]]);
38 delete params[keyLookup[normalisedParam]];
39 });
40
41 return templated;
42}
43
44module.exports = exports = {
45 templateParams: templateParams,
46 template: template
47};
48