The openapi-v3-react-query library is designed to simplify the integration of OpenAPI V3 specifications with React Query.
npm install openapi-v3-react-querybash
npm i -D openapi-v3-typescript
`
And in your tsconfig.json add alias for axios instance:
`diff
{
"compilerOptions": {
"paths": {
+ "@api-instance": ["path-to-your-api-instance"]
}
}
}
`
Configuration Options
In the root directory of your project, you will find the openapi-v3-typescript-config.json file. This file is crucial for configuring the OpenAPI TypeScript generation process. Here’s how to set it up:
$3
- Specify your input schema in JSON or YAML format, You can provide:
- A local path: ./path/to/schema.json
- A remote URL: https://api.test.com/swagger/v1/swagger.json
$3
- Indicate the directory where you would like the output to be saved. Example: ./openapi-v3-typescript
- Default value: ./openapi-v3-typescript
$3
- Provide a function that takes an API route as a parameter and returns the corresponding controller name.
- Default value: (route) => route.split('/')[2]
$3
Configuration for enabling @tanstack/react-query, which contains the following properties:
#### - enable
- Enable or disable @tanstack/react-query.
- Default value: true
#### - pageParam
- This parameter is for handling infinite queries and may vary between projects based on backend implementation.
- Default value: pageParam
#### - getNextPageParam
- This function is used to determine the next page's parameters based on the last page of data that was fetched.
- Default value: (lastPage, allPages) => {
Usage
- To generate types from your OpenAPI specification, run:
`bash
npx openapi-v3-typescript fetch
`
- To generate types for a specific controller, use the following command:
`bash
npx openapi-v3-typescript fetch
`
▎Note
second command will not create the common.interface.ts file.
Project Structure
For each controller, a dedicated folder will be generated, which will include the following four files:
- \.api-routes.ts: Contains the API routes associated with the controller.
- \.api.ts: Contains API handler using Axios.
- \.interface.ts: Contains controller interfaces.
- \.queries.ts: This optional file includes queries implemented using @tanstack/react-query.
Furthermore, a common.interface.ts file will be provided to prevent import cycles.
Advanced
- ### Override API parameters:
To override parameters utilize the axiosConfig parameter in the following manner:
`ts
// user.api.ts
const signIn = async (
payload: IUserSignInRequest,
axiosConfig?: AxiosRequestConfig
) => {
const { data } = await ApiInstance.post(
UserApiRoutes.SignIn,
payload.bodyPayload,
axiosConfig
);
return data;
};
const userApi = {
signIn,
};
export default userApi;
`
#### Example Usage:
`diff
userApi.signIn(
{
bodyPayload: {
email: "openapi@gmail.com",
password: "",
},
},
+ {
+ params: {
+ someParameter: "some value",
+ },
+ headers: {
+ "header-parameter": "header parameter value",
+ },
+ }
);
`
- ### Override Query parameters:
Override Query Options:
`ts
// user.queries.ts
const useGetAllUserQuery = (options?: UseQueryOptions) =>
useQuery({
queryKey: userQueryKeys.useGetAllUserQuery(),
queryFn: () => userApi.getAllUser(),
...options,
});
`
#### Example Usage:
`diff
+ const {data, isLoading} = useGetAllUserQuery({
+ refetchOnMount: true,
+ })
`
- ### Query Keys
Each query comes with exported queryKeys for convenient use when invalidating queries, helping to prevent human errors in writing query keys and ensuring successful refetching of the query.
`ts
// country.queries.ts
export const countryQueryKeys = {
useGetAllCityQuery: (payload: ICountryGetAllCityRequest) => [
"useGetAllCityQuery",
payload,
],
};
`
#### Example Usage:
`diff
+ import { countryQueryKeys } from '/.../country/country.queries.ts';
...
const queryClient = useQueryClient();
...
queryClient.invalidateQueries(
+ countryQueryKeys.useGetAllCityQuery({
+ countryId: 3,
+ })
);
`
- ### apiNameConverter
The apiNameConverter allows you to customize the naming of your API endpoints to fit your specific needs.
- Default value: (apiName) => apiName
#### Example Usage:
You can modify the API name by replacing certain text within it. For instance:
`json
"apiNameConverter": "(apiName) => apiName.replace(/some text/gi, 'another text')"
`
▎Note
The apiNameConverter will impact not only the api names but also the route names and interface names and query names.
- ### interfaceNameConverter
The interfaceNameConverter provides a way to customize the naming of interfaces according to your preferences.
- Default value: (interfaceName) => interfaceName
#### Example Usage:
Similar to the apiNameConverter, you can replace specific text in the interface names:
`json
"interfaceNameConverter": "(interfaceName) => interfaceName.replace(/some text/gi, 'another text')"
`
- ### includedControllers: []
Specifies an array of controllers to be included in the generated output. Only the controllers listed in this array will be generated.
- ### excludedControllers: []
Specifies an array of controllers to be excluded from the generated output. All controllers except those listed in this array will be generated.
- ### Omit Generation of Specific List of Controllers
To exclude the generation of specific controllers, such as those related to the dashboard, you can utilize the getControllerNameFromRoute function within the openapi-v3-typescript-config.json file. When getControllerNameFromRoute returns null, the controller will not be generated.
`diff
// openapi-v3-typescript-config.json
{
+ "getControllerNameFromRoute": "(route) => route.split('/')[2].startsWith('Dashboard') ? null : route.split('/')[2]"
}
``