Skip to content

Commit

Permalink
collectVars API in url replacements (#3178)
Browse files Browse the repository at this point in the history
* collectVars API in url replacements

* minor fixes
  • Loading branch information
dvoytenko committed May 10, 2016
1 parent bbc75d5 commit 2afa6d2
Show file tree
Hide file tree
Showing 2 changed files with 50 additions and 0 deletions.
30 changes: 30 additions & 0 deletions src/service/url-replacements-impl.js
Original file line number Diff line number Diff line change
Expand Up @@ -434,6 +434,17 @@ class UrlReplacements {
* @return {!Promise<string>}
*/
expand(url, opt_bindings) {
return this.expand_(url, opt_bindings);
}

/**
* @param {string} url
* @param {!Object<string, *>=} opt_bindings
* @param {!Object<string, *>=} opt_collectVars
* @return {!Promise<string>}
* @private
*/
expand_(url, opt_bindings, opt_collectVars) {
const expr = this.getExpr_(opt_bindings);
let replacementPromise;
const encodeValue = val => {
Expand Down Expand Up @@ -467,6 +478,9 @@ class UrlReplacements {
rethrowAsync(err);
}).then(v => {
url = url.replace(match, encodeValue(v));
if (opt_collectVars) {
opt_collectVars[match] = v;
}
});
if (replacementPromise) {
replacementPromise = replacementPromise.then(() => p);
Expand All @@ -475,6 +489,9 @@ class UrlReplacements {
}
return match;
}
if (opt_collectVars) {
opt_collectVars[match] = val;
}
return encodeValue(val);
});

Expand All @@ -485,6 +502,19 @@ class UrlReplacements {
return replacementPromise || Promise.resolve(url);
}

/**
* Collects all substitutions in the provided URL and expands them to the
* values for known variables. Optional `opt_bindings` can be used to add
* new variables or override existing ones.
* @param {string} url
* @param {!Object<string, *>=} opt_bindings
* @return {!Promise<!Object<string, *>>}
*/
collectVars(url, opt_bindings) {
const vars = Object.create(null);
return this.expand_(url, opt_bindings, vars).then(() => vars);
}

/**
* @param {string} name
* @return {function(*):*}
Expand Down
20 changes: 20 additions & 0 deletions test/functional/test-url-replacements.js
Original file line number Diff line number Diff line change
Expand Up @@ -615,6 +615,26 @@ describe('UrlReplacements', () => {
});
});

it('should collect vars', () => {
const win = getFakeWindow();
win.location = parseUrl('https://example.com?p1=foo');
return installUrlReplacementsService(win)
.collectVars('?SOURCE_HOST&QUERY_PARAM(p1)&SIMPLE&FUNC&PROMISE', {
'SIMPLE': 21,
'FUNC': () => 22,
'PROMISE': () => Promise.resolve(23),
})
.then(res => {
expect(res).to.deep.equal({
'SOURCE_HOST': 'example.com',
'QUERY_PARAM(p1)': 'foo',
'SIMPLE': 21,
'FUNC': 22,
'PROMISE': 23,
});
});
});

describe('access values', () => {

let accessService;
Expand Down

0 comments on commit 2afa6d2

Please sign in to comment.