Skip to content

feat(openapi-fetch): add global querySerializer option (#1182) #1183

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

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: 5 additions & 0 deletions .changeset/four-carpets-push.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
"openapi-fetch": minor
---

Add global `querySerializer()` option to `createClient()`
29 changes: 29 additions & 0 deletions packages/openapi-fetch/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -188,6 +188,35 @@ Note that this happens **at the request level** so that you still get correct ty

_Thanks, [@ezpuzz](https://github.com/ezpuzz)!_

Provide a `querySerializer()` to `createClient()` to globally override the default `URLSearchParams` serializer. Serializers provided to a specific request method still override the global default.

```ts
import createClient, { defaultSerializer } from "openapi-fetch";
import { paths } from "./v1"; // generated from openapi-typescript
import { queryString } from "query-string";

const { get, post } = createClient<paths>({
baseUrl: "https://myapi.dev/v1/",
querySerializer: (q) => queryString.stringify(q, { arrayFormat: "none" }), // Override the default `URLSearchParams` serializer
});

const { data, error } = await get("/posts/", {
params: {
query: { categories: ["dogs", "cats", "lizards"] }, // Use the serializer specified in `createClient()`
},
});

const { data, error } = await get("/images/{image_id}", {
params: {
path: { image_id: "image-id" },
query: { size: 512 },
},
querySerializer: defaultSerializer, // Use `openapi-fetch`'s `URLSearchParams` serializer
});
```

_Thanks, [@psychedelicious](https://github.com/psychedelicious)!_

## Examples

### 🔒 Handling Auth
Expand Down
31 changes: 31 additions & 0 deletions packages/openapi-fetch/src/index.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -387,6 +387,37 @@ describe("client", () => {

expect(fetchMocker.mock.calls[0][0]).toBe("/blogposts/my-post?alpha=2&beta=json");
});

it("applies global serializer", async () => {
const client = createClient<paths>({
querySerializer: (q) => `alpha=${q.version}&beta=${q.format}`,
});
mockFetchOnce({ status: 200, body: "{}" });
await client.get("/blogposts/{post_id}", {
params: {
path: { post_id: "my-post" },
query: { version: 2, format: "json" },
},
});

expect(fetchMocker.mock.calls[0][0]).toBe("/blogposts/my-post?alpha=2&beta=json");
});

it("overrides global serializer if provided", async () => {
const client = createClient<paths>({
querySerializer: () => "query",
});
mockFetchOnce({ status: 200, body: "{}" });
await client.get("/blogposts/{post_id}", {
params: {
path: { post_id: "my-post" },
query: { version: 2, format: "json" },
},
querySerializer: (q) => `alpha=${q.version}&beta=${q.format}`,
});

expect(fetchMocker.mock.calls[0][0]).toBe("/blogposts/my-post?alpha=2&beta=json");
});
});
});

Expand Down
6 changes: 4 additions & 2 deletions packages/openapi-fetch/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,8 @@ interface ClientOptions extends RequestInit {
baseUrl?: string;
/** custom fetch (defaults to globalThis.fetch) */
fetch?: typeof fetch;
/** global querySerializer */
querySerializer?: QuerySerializer<unknown>;
}
export interface BaseParams {
params?: { query?: Record<string, unknown> };
Expand Down Expand Up @@ -82,15 +84,15 @@ export function createFinalURL<O>(url: string, options: { baseUrl?: string; para
}

export default function createClient<Paths extends {}>(clientOptions: ClientOptions = {}) {
const { fetch = globalThis.fetch, ...options } = clientOptions;
const { fetch = globalThis.fetch, querySerializer: globalQuerySerializer, ...options } = clientOptions;

const defaultHeaders = new Headers({
...DEFAULT_HEADERS,
...(options.headers ?? {}),
});

async function coreFetch<P extends keyof Paths, M extends HttpMethod>(url: P, fetchOptions: FetchOptions<M extends keyof Paths[P] ? Paths[P][M] : never>): Promise<FetchResponse<M extends keyof Paths[P] ? Paths[P][M] : unknown>> {
const { headers, body: requestBody, params = {}, parseAs = "json", querySerializer = defaultSerializer, ...init } = fetchOptions || {};
const { headers, body: requestBody, params = {}, parseAs = "json", querySerializer = globalQuerySerializer ?? defaultSerializer, ...init } = fetchOptions || {};

// URL
const finalURL = createFinalURL(url as string, { baseUrl: options.baseUrl, params, querySerializer });
Expand Down