Fetch client: Support fetch function injection
Description
Just like #2848, the fetch client should also support dependency injection.
I would like to inject the generated APIs with a fetch function that adds authentication headers and sets base URL for the API at runtime. Something like the following function in a factory class that provides the rest of the application with the API:
const customFetch = (url, options) => {
return fetch(new URL(url, this.appConfig.getApiBaseUrl()), {...options, ...this.authenticator.getAuthHeaders()});
}Current behavior
The generated API is a collection of plain functions that call fetch() directly. Recently, we got a parameter to replace the fetch function; however, this still means that every API call needs to receive this new function:
import {getSomething} from "./api";
const data = getSomething({name}, addAuthHeaders({...options}), fetchFnWithBaseDir);The currently generated API:
export const getSomething = async ( options?: RequestInit, fetchFn?: typeof globalThis.fetch): Promise<getSomethingResponseSuccess> => {
const res = await (fetchFn ?? fetch)(getGetSomethingUrl(),
// ...
}Proposed behavior
Generate factory functions that accept the fetch function as a parameter, allowing runtime dependency injection:
export const createSomethingApi(fetchFn?: typeof globalThis.fetch) => ({
getSomething: async ( options?: RequestInit ): Promise<getSomethingResponseSuccess> => {
const res = await (fetchFn ?? fetch)(getGetSomethingUrl(),
// ... no changes in the function body
},
});Then the usage of the API is much easier:
// Prepare the API
const api = createSomethingApi(customFetch);
// ... and everywhere else it is just:
const data = await api.getSomething(name);Proposed solution
There shall be the same option for the fetch client just like the one #2848 introduced: httpClientInjection: 'factory'
The change is only how the fetchFn is provided to the generated functions -- a closure (factory) instead of the parameter.
Source: orval-labs/orval