Skip to content

Commit

Permalink
Parse URL params properly (#183)
Browse files Browse the repository at this point in the history
Co-authored-by: Justin Vartanian <justin.vartanian.ext@bayer.com>
  • Loading branch information
jvartanian and Justin Vartanian authored Apr 11, 2023
1 parent 1114614 commit dc9ed19
Show file tree
Hide file tree
Showing 2 changed files with 9 additions and 18 deletions.
2 changes: 1 addition & 1 deletion src/web-utils.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -191,7 +191,7 @@ describe("Url param extraction", () => {
const foo = WebUtils.randomString();
const paramObj = WebUtils.getUrlParams(`https://app.example.com?random=${random}&foo=${foo}#ignored`);
expect(paramObj!["random"]).toStrictEqual(random);
expect(paramObj!["foo"]).toStrictEqual(`${foo}#ignored`);
expect(paramObj!["foo"]).toStrictEqual(`${foo}`);
});

it('should use hash flag and ignore query flag', () => {
Expand Down
25 changes: 8 additions & 17 deletions src/web-utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -60,33 +60,24 @@ export class WebUtils {
* Public only for testing
*/
static getUrlParams(url: string): { [x: string]: string; } | undefined {
const urlString = `${url}`.trim();
const urlString = `${url ?? ''}`.trim();

if (urlString.length === 0) {
return;
}

// #132
let hashIndex = urlString.indexOf("#");
let queryIndex = urlString.indexOf("?");

if (hashIndex === -1 && queryIndex === -1) {
const parsedUrl = new URL(urlString);
if (!parsedUrl.search && !parsedUrl.hash) {
return;
}
let paramsIndex: number;
if (hashIndex > -1 && queryIndex === -1) {
paramsIndex = hashIndex;
} else if (queryIndex > -1 && hashIndex === -1) {
paramsIndex = queryIndex;
} else {
paramsIndex = hashIndex > -1 && hashIndex < queryIndex ? hashIndex : queryIndex;
}

if (urlString.length <= paramsIndex + 1) {
return;
let urlParamStr;
if (parsedUrl.search) {
urlParamStr = parsedUrl.search.substr(1);
} else {
urlParamStr = parsedUrl.hash.substr(1);
}

const urlParamStr = urlString.slice(paramsIndex + 1);
const keyValuePairs: string[] = urlParamStr.split(`&`);
// @ts-ignore
return keyValuePairs.reduce((accumulator, currentValue) => {
Expand Down

0 comments on commit dc9ed19

Please sign in to comment.