Skip to content
This repository was archived by the owner on Dec 8, 2022. It is now read-only.

Stopping same param from getting added more than once #182

Merged
merged 4 commits into from
Jun 15, 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.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 8 additions & 0 deletions runtime/params.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,14 @@ describe('SkyAppRuntimeConfigParams', () => {
expect(params.getUrl('https://mysite.com?c=d')).toEqual('https://mysite.com?c=d&a1=b');
});

it('should not add a current param if the url already has it', () => {
const params: SkyAppRuntimeConfigParams = new SkyAppRuntimeConfigParams(
'?a1=b',
allowed
);
expect(params.getUrl('https://mysite.com?a1=c&a3=e')).toEqual('https://mysite.com?a1=c&a3=e');
});

it('should add the current params to a url without a querystring', () => {
const params: SkyAppRuntimeConfigParams = new SkyAppRuntimeConfigParams(
'?a1=b',
Expand Down
27 changes: 19 additions & 8 deletions runtime/params.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,19 @@
import { URLSearchParams } from '@angular/http';

/**
* Given a "url" (could be just querystring, or fully qualified),
* Returns the extracted URLSearchParams.
* @param {string} url
* @return {URLSearchParams} urlSearchParams
*/
function getUrlSearchParams(url: string): URLSearchParams {
if (url.indexOf('?') > -1) {
url = url.split('?')[1];
}

return new URLSearchParams(url);
}

export class SkyAppRuntimeConfigParams {

private params: {[key: string]: string} = {};
Expand All @@ -9,13 +23,7 @@ export class SkyAppRuntimeConfigParams {
private allowed: string[]
) {

// Find just the querystring portion of the url
if (this.url.indexOf('?') > -1) {
this.url = this.url.split('?')[1];
}

// Let angular convert string into object
const urlSearchParams: URLSearchParams = new URLSearchParams(this.url);
const urlSearchParams: URLSearchParams = getUrlSearchParams(url);

// Filter to allowed params
this.allowed.forEach(key => {
Expand Down Expand Up @@ -63,11 +71,14 @@ export class SkyAppRuntimeConfigParams {
* @returns {string} url
*/
public getUrl(url: string): string {
const urlSearchParams: URLSearchParams = getUrlSearchParams(url);
const delimiter = url.indexOf('?') === -1 ? '?' : '&';
let joined: string[] = [];

this.getAllKeys().forEach(key => {
joined.push(`${key}=${encodeURIComponent(this.get(key))}`);
if (!urlSearchParams.has(key)) {
joined.push(`${key}=${encodeURIComponent(this.get(key))}`);
}
});

return joined.length === 0 ? url : `${url}${delimiter}${joined.join('&')}`;
Expand Down