From 71392cd0b1a6ffb414fbb3f02b17c045871d4cf9 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jo=C3=A3o=20Louren=C3=A7o?= Date: Mon, 22 May 2023 10:36:15 +0000 Subject: [PATCH] fix: parse an url who already have params FIX: Add params to an url who already have params #151 --- src/index.ts | 11 +++++++++-- test/github-issue/151.ts | 11 +++++++++++ 2 files changed, 20 insertions(+), 2 deletions(-) create mode 100644 test/github-issue/151.ts diff --git a/src/index.ts b/src/index.ts index 64a2480..324d498 100644 --- a/src/index.ts +++ b/src/index.ts @@ -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; } @@ -268,7 +268,14 @@ function removeNullOrUndef

(params: P) { return Object.assign(result, { [key]: value }); }, {} as { [K in keyof P]: NonNullable }); } - + +function preparePathAndQuery(renderedPath: string, renderedQuery: string) { + const renderedPathCleanded = join(renderedPath, '?', ''); + const delimiter = /\?/.test(renderedPathCleanded) ? '&' : '?'; + const pathAndQuery = join(renderedPathCleanded, delimiter, renderedQuery); + return pathAndQuery; +} + function nullOrUndefined(v: T) { return v === undefined || v === null; } diff --git a/test/github-issue/151.ts b/test/github-issue/151.ts new file mode 100644 index 0000000..83c3d3b --- /dev/null +++ b/test/github-issue/151.ts @@ -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) + +});