Skip to content

Commit

Permalink
fix: parse an url who already have params
Browse files Browse the repository at this point in the history
FIX: Add params to an url who already have params balazsbotond#151
  • Loading branch information
jrel committed May 22, 2023
1 parent d5834df commit 71392cd
Show file tree
Hide file tree
Showing 2 changed files with 20 additions and 2 deletions.
11 changes: 9 additions & 2 deletions src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -147,7 +147,7 @@ function urlcatImpl(
const { renderedPath, remainingParams } = path(pathTemplate, params);
const cleanParams = removeNullOrUndef(remainingParams);
const renderedQuery = query(cleanParams, config);
const pathAndQuery = join(renderedPath, '?', renderedQuery);
const pathAndQuery = preparePathAndQuery(renderedPath, renderedQuery);

return baseUrl ? joinFullUrl(renderedPath, baseUrl, pathAndQuery) : pathAndQuery;
}
Expand Down Expand Up @@ -268,7 +268,14 @@ function removeNullOrUndef<P extends ParamMap>(params: P) {
return Object.assign(result, { [key]: value });
}, {} as { [K in keyof P]: NonNullable<P[K]> });
}


function preparePathAndQuery(renderedPath: string, renderedQuery: string) {
const renderedPathCleanded = join(renderedPath, '?', '');
const delimiter = /\?/.test(renderedPathCleanded) ? '&' : '?';
const pathAndQuery = join(renderedPathCleanded, delimiter, renderedQuery);
return pathAndQuery;
}

function nullOrUndefined<T>(v: T) {
return v === undefined || v === null;
}
11 changes: 11 additions & 0 deletions test/github-issue/151.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
import urlcat from '../../src';

it('Add params to an url who already have params', () => {

const url = 'http://myurl.com?myparams=1'
const result = urlcat(url, { foo: 2, bar: 3 })
const expected = "http://myurl.com?myparams=1&foo=2&bar=3"

expect(result).toEqual(expected)

});

0 comments on commit 71392cd

Please sign in to comment.