Custom Query Param Serialization in fetch Client #2368
|
Hi everyone, I’m using Orval with the fetch client and noticed a limitation with query parameter serialization. The generated code uses URLSearchParams.toString(), which doesn’t support indexed arrays or custom formats: I know Orval allows providing a custom fetch client, but the challenge is that it still generates the full URL and passes that to my custom fetch. To apply custom serialization, I’d have to parse the URL back into parameters, reserialize them in my desired format, and then reconstruct the URL which feels redundant and less optimal. Is there a known pattern for handling this that I'm missing? |
Replies: 2 comments 2 replies
|
i think custom fetch client is the way to go. |
|
You should not need to parse the already-built URL in a custom fetch client anymore. Orval has a request-level Example: // orval.config.ts
import { defineConfig } from 'orval'
export default defineConfig({
api: {
input: './openapi.yaml',
output: {
client: 'fetch',
target: './src/api.ts',
override: {
paramsSerializer: {
path: './src/custom-params-serializer.ts',
name: 'customParamsSerializer',
},
},
},
},
})// src/custom-params-serializer.ts
import qs from 'qs'
export const customParamsSerializer = (
params: Record<string, unknown> | undefined,
): string => {
return qs.stringify(params ?? {}, {
arrayFormat: 'indices', // foo[0]=a&foo[1]=b
skipNulls: true,
encodeValuesOnly: true,
})
}For the fetch client, the serializer must return the raw query string without the leading If only a few endpoints need this, put the same |
You should not need to parse the already-built URL in a custom fetch client anymore. Orval has a request-level
override.paramsSerializerhook that is valid for the fetch client too.Example: