Skip to content

Commit

Permalink
feat: Handle native URLSearchParams passed as Query Params
Browse files Browse the repository at this point in the history
  • Loading branch information
MattCCC committed Aug 22, 2024
1 parent e1ec430 commit efb54b8
Show file tree
Hide file tree
Showing 3 changed files with 24 additions and 1 deletion.
5 changes: 4 additions & 1 deletion src/types/api-handler.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,10 @@ import type {
} from './request-handler';

// Common type definitions
export declare type QueryParams<T = unknown> = Record<string, T> | null;
export declare type QueryParams<T = unknown> =
| Record<string, T>
| URLSearchParams
| null;
export declare type BodyPayload<T = unknown> = Record<string, T> | null;
export declare type QueryParamsOrBody<T = unknown> =
| QueryParams<T>
Expand Down
11 changes: 11 additions & 0 deletions src/utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,17 @@ export function appendQueryParams(url: string, params: QueryParams): string {
return url;
}

// Check if `params` is an instance of URLSearchParams and bail early if it is
if (params instanceof URLSearchParams) {
const encodedQueryString = params.toString();

return url.includes('?')
? `${url}&${encodedQueryString}`
: encodedQueryString
? `${url}?${encodedQueryString}`
: url;
}

// This is exact copy of what JQ used to do. It works much better than URLSearchParams
const s = [];
const add = function (k: string, v: any) {
Expand Down
9 changes: 9 additions & 0 deletions test/utils.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -279,6 +279,15 @@ describe('Utils', () => {
);
});

it('should handle params as an instance of URLSearchParams', () => {
const url = 'https://api.example.com/resource';
const params = new URLSearchParams();
params.append('foo', 'bar');
params.append('baz', 'qux');
const result = appendQueryParams(url, params);
expect(result).toBe('https://api.example.com/resource?foo=bar&baz=qux');
});

it('should handle complex nested parameters', () => {
const url = 'https://api.example.com/resource';
const params = { nested: { foo: 'bar', baz: [1, 2] } };
Expand Down

0 comments on commit efb54b8

Please sign in to comment.