Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: Handle native URLSearchParams passed as Query Params #45

Merged
merged 1 commit into from
Aug 22, 2024
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
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
Loading