This is a utility library meant to be used with RTK Query that will generate a typed API client from an OpenAPI schema.
Create an empty api using createApi
like
// Or from '@reduxjs/toolkit/query' if not using the auto-generated hooks
import { createApi, fetchBaseQuery } from '@reduxjs/toolkit/query/react';
// initialize an empty api service that we'll inject endpoints into later as needed
export const emptySplitApi = createApi({
baseQuery: fetchBaseQuery({ baseUrl: '/' }),
endpoints: () => ({}),
});
Generate a config file (json, js or ts) with contents like
import { ConfigFile } from '@rtk-incubator/rtk-query-codegen-openapi';
const config: ConfigFile = {
schemaFile: 'https://petstore3.swagger.io/api/v3/openapi.json',
apiFile: './src/store/emptyApi.ts',
apiImport: 'emptyApi',
outputFile: './src/store/petApi.ts',
exportName: 'petApi',
hooks: true,
};
export default config;
and then call the code generator:
npx @rtk-incubator/rtk-query-codegen-openapi openapi-config.ts
import { generateEndpoints } from '@rtk-incubator/rtk-query-codegen-openapi';
const api = await generateEndpoints({
apiFile: './fixtures/emptyApi.ts',
schemaFile: resolve(__dirname, 'fixtures/petstore.json'),
filterEndpoints: ['getPetById', 'addPet'],
hooks: true,
});
interface SimpleUsage {
apiFile: string;
schemaFile: string;
apiImport?: string;
exportName?: string;
argSuffix?: string;
responseSuffix?: string;
hooks?: boolean;
outputFile: string;
filterEndpoints?: string | RegExp | (string | RegExp)[];
endpointOverrides?: EndpointOverrides[];
}
If you only want to include a few endpoints, you can use the filterEndpoints
config option to filter your endpoints.
const filteredConfig: ConfigFile = {
// ...
// should only have endpoints loginUser, placeOrder, getOrderById, deleteOrder
filterEndpoints: ['loginUser', /Order/],
};
If an endpoint is generated as a mutation instead of a query or the other way round, you can override that:
const withOverride: ConfigFile = {
// ...
endpointOverrides: [
{
pattern: 'loginUser',
type: 'mutation',
},
],
};
const config: ConfigFile = {
schemaFile: 'https://petstore3.swagger.io/api/v3/openapi.json',
apiFile: './src/store/emptyApi.ts',
outputFiles: {
'./src/store/user.js': {
filterEndpoints: [/user/i],
},
'./src/store/order.js': {
filterEndpoints: [/order/i],
},
'./src/store/pet.js': {
filterEndpoints: [/pet/i],
},
},
};
View the RTK Query Code Generation docs
TODO these need to be updated!