Code Generation
Code Generation
OpenAPI
curl -o petstore.json https://petstore3.swagger.io/api/v3/openapi.json
npx @rtk-incubator/rtk-query-codegen-openapi --hooks petstore.json > petstore-api.generated.ts// file: petstore-api.generated.ts noEmit
export * from 'petstore-api.generated'
// file: petstoreApi.ts
import { api as generatedApi } from './petstore-api.generated'
export const api = generatedApi.enhanceEndpoints({
addTagTypes: ['Pet'],
endpoints: {
// basic notation: just specify properties to be overridden
getPetById: {
providesTags: (result, error, arg) => [{ type: 'Pet', id: arg.petId }],
},
findPetsByStatus: {
providesTags: (result) =>
// is result available?
result
? // successful query
[
{ type: 'Pet', id: 'LIST' },
...result.map((pet) => ({ type: 'Pet' as const, id: pet.id })),
]
: // an error occurred, but we still want to refetch this query when `{ type: 'Pet', id: 'LIST' }` is invalidated
[{ type: 'Pet', id: 'LIST' }],
},
// alternate notation: callback that gets passed in `endpoint` - you can freely modify the object here
addPet: (endpoint) => {
endpoint.invalidatesTags = (result) =>
result ? [{ type: 'Pet', id: result.id }] : []
},
updatePet: {
invalidatesTags: (result, error, arg) => [
{ type: 'Pet', id: arg.pet.id },
],
},
deletePet: {
invalidatesTags: (result, error, arg) => [{ type: 'Pet', id: arg.petId }],
},
},
})
export const {
useGetPetByIdQuery,
useFindPetsByStatusQuery,
useAddPetMutation,
useUpdatePetMutation,
useDeletePetMutation,
} = apiGraphQL
Last updated