|
I'm using Orval inside a Turborepo, and it's working great to generate typed API functions from my OpenAPI spec. The problem I'm running into is that the generated functions are just plain functions, which means I have to import and call them directly everywhere. What I’d really like is to have a generated API client (e.g. apiClient) that wraps those functions, so that each consumer of the package can: Initialize a client once, providing options like baseUrl and headers (for things like auth tokens). Use the generated client to access all endpoints in a consistent way, for example: import { createApiClient } from "@repo/api-client";
const client = createApiClient({
baseUrl: process.env.API_URL,
headers: {
Authorization: `Bearer ${token}`,
},
});
await client.foo id: '123' });
await client.bar({ title: 'Hello' });instead of import { foo, bar} from "@repo/api-client";
await foo id: '123' });
await bar({ title: 'Hello' });Is there currently a way to do this with Orval? If not, would it make sense as a feature request? I think it could really improve DX, especially in monorepo setups. |
Replies: 1 comment
|
Orval does not currently generate a first-class The usual Orval way to solve the For axios, you can put the runtime configuration in your own axios instance/mutator: // src/api/mutator/custom-instance.ts
import Axios, { AxiosRequestConfig } from 'axios';
export const api = Axios.create();
export const setApiClientConfig = (config: { baseURL?: string; token?: string }) => {
api.defaults.baseURL = config.baseURL;
api.defaults.headers.common.Authorization = config.token
? `Bearer ${config.token}`
: undefined;
};
export const customInstance = <T>(config: AxiosRequestConfig): Promise<T> => {
return api(config).then(({ data }) => data);
};and configure Orval: output: {
client: 'axios',
target: './src/client/api',
schemas: './src/client/types',
override: {
mutator: {
path: './src/api/mutator/custom-instance.ts',
name: 'customInstance',
},
},
}Then consumers can call your setup function once before using the generated functions: import { setApiClientConfig } from './api/mutator/custom-instance';
import { foo, bar } from '@repo/api-client';
setApiClientConfig({ baseURL: process.env.API_URL, token });
await foo({ id: '123' });
await bar({ title: 'Hello' });If you specifically want |
Orval does not currently generate a first-class
createApiClient()object/factory in the shape from your example. The generated API surface is still operation functions/hooks.The usual Orval way to solve the
baseUrl/ headers / auth-token part is a custom mutator (or, for fetch,baseUrl.runtimeif all you need is runtime base URL resolution).For axios, you can put the runtime configuration in your own axios instance/mutator: