-
Notifications
You must be signed in to change notification settings - Fork 13
Description
I can define a custom baseQuery function or I can use the defaults which creates an instance of a fetchBaseQuery with the baseUrl from the OpenAPI spec.
I'm wondering if it's possible to define a plug-in replacement for fetchBaseQuery. That is, a factory function which is called with FetchBaseQueryArgs or { baseUrl: string } and returns a base query function.
export const createBaseQuery = ({baseUrl, ...rest}: FetchBaseQueryArgs) => {
return fetchBaseQuery({
baseUrl: getRootUrl() + baseUrl,
prepareHeaders: (headers, { getState }) => {
headers.set('Content-Type', 'application/json');
// access token stored in redux
const userToken = (getState() as {auth: AuthState}).auth?.token;
if (userToken) {
headers.set('Authorization', `Bearer ${userToken}`);
}
return headers;
},
...rest,
})
}
I'm dealing with an API setup that is unusual and kind of maddening. Each section of the API is defined independently and has a separate OpenAPI spec, so I am having to run the codegen multiple times. Each API should have the same prepareHeaders function but a different baseUrl. Additionally, the root URL for all APIs varies based on the environment where the code is executed (via the getRootUrl()) function above.
I am trying something like this, but I can't figure out how to create the correct baseQuery or how to override it without touching the generated file.
package.json
"scripts": {
"generate": "node generate.js"
},
generate.js
const {execSync} = require('child_process');
const DIR = "./src/schemas";
const QUERY = "./src/utils/API.ts:baseQuery";
const generateAPI = (slug, version = "v1") => {
const generated = `${DIR}/${slug}.generated.ts`;
const remote = `https://api.mydomain.com/${slug}/${version}/openapi.json`;
console.log(`downloading ${remote}`);
console.log(`creating API ${generated}`);
execSync(`npx @rtk-incubator/rtk-query-codegen-openapi --reducerPath ${slug} --baseQuery ${QUERY} --hooks --file ${generated} ${remote}`);
}
generateAPI("first-endpoint");
generateAPI("second-endpoint");
// etc...