Skip to content

Commit 93a67ba

Browse files
committed
improve api manager support for search params
1 parent 12b88eb commit 93a67ba

File tree

2 files changed

+12
-4
lines changed

2 files changed

+12
-4
lines changed

src/managers/api.ts

Lines changed: 11 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -11,9 +11,8 @@ export class APIManager {
1111
}
1212

1313
async request<T>(path: string, options: APIRequestInit = {}) {
14-
const params = new URLSearchParams(options.params).toString();
14+
const { init, params } = this.parseOptions(options);
1515
const url = new URL(`${path}?${params}`, this.baseUrl);
16-
const init = this.parseOptions(options);
1716

1817
const response = await fetch(url, init);
1918
const data: APIPayload<T> = await response.json();
@@ -25,6 +24,15 @@ export class APIManager {
2524
}
2625

2726
private parseOptions(options: APIRequestInit) {
27+
const paramsObject =
28+
options.params &&
29+
Object.fromEntries(
30+
Object.entries(options.params)
31+
.filter(([, value]) => Boolean(value))
32+
.map(([key, value]) => [key, String(value)]),
33+
);
34+
const params = new URLSearchParams(paramsObject).toString();
35+
2836
const { method, headers, body, ...rest } = options;
2937
const init: RequestInit = {
3038
method: method || "GET",
@@ -36,6 +44,6 @@ export class APIManager {
3644
init.body = body instanceof FormData ? body : JSON.stringify(body);
3745
}
3846

39-
return init;
47+
return { init, params };
4048
}
4149
}

src/types/api.ts

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
export type APIRequestInit = Omit<RequestInit, "method" | "body"> & {
22
method?: "GET" | "POST" | "PUT" | "PATCH" | "DELETE";
3-
params?: Record<string, string>;
3+
params?: Record<string, string | number | boolean | undefined>;
44
body?: object | FormData;
55
};
66

0 commit comments

Comments
 (0)