Skip to content

Commit 6a90c3f

Browse files
committed
docs
1 parent 9e79156 commit 6a90c3f

File tree

2 files changed

+120
-171
lines changed

2 files changed

+120
-171
lines changed

docs/rtk-query/usage/code-generation.mdx

Lines changed: 120 additions & 51 deletions
Original file line numberDiff line numberDiff line change
@@ -14,70 +14,139 @@ RTK Query's API and architecture is oriented around declaring API endpoints up f
1414

1515
We have early previews of code generation capabilities available as separate tools.
1616

17+
## GraphQL
18+
19+
We provide a [Plugin for GraphQL Codegen](https://www.graphql-code-generator.com/docs/plugins/typescript-rtk-query). You can find the documentation to that on the graphql-codegen homepage.
20+
21+
For a full example on how to use it, you can see [this example project](https://github.com/reduxjs/redux-toolkit/tree/master/examples/query/react/graphql-codegen).
22+
1723
## OpenAPI
1824

19-
We have a first version of a code generator from OpenAPI schemas over at [`rtk-incubator/rtk-query-codegen`](https://github.com/rtk-incubator/rtk-query-codegen).
25+
We provide a package for RTK Query code generation from OpenAPI schemas. It is published as `@rtk-query/codegen-openapi` and you can find the source code at [`packages/rtk-query-codegen-openapi`](https://github.com/reduxjs/redux-toolkit/tree/master/packages/rtk-query-codegen-openapi).
26+
27+
### Usage
28+
29+
Create an empty api using `createApi` like
30+
31+
```ts
32+
// Or from '@reduxjs/toolkit/query' if not using the auto-generated hooks
33+
import { createApi, fetchBaseQuery } from '@reduxjs/toolkit/query/react'
34+
35+
// initialize an empty api service that we'll inject endpoints into later as needed
36+
export const emptySplitApi = createApi({
37+
baseQuery: fetchBaseQuery({ baseUrl: '/' }),
38+
endpoints: () => ({}),
39+
})
40+
```
2041

21-
You can create an api by running:
42+
Generate a config file (json, js or ts) with contents like
43+
44+
```ts
45+
import { ConfigFile } from '@rtk-incubator/rtk-query-codegen-openapi'
46+
47+
const config: ConfigFile = {
48+
schemaFile: 'https://petstore3.swagger.io/api/v3/openapi.json',
49+
apiFile: './src/store/emptyApi.ts',
50+
apiImport: 'emptyApi',
51+
outputFile: './src/store/petApi.ts',
52+
exportName: 'petApi',
53+
hooks: true,
54+
}
55+
56+
export default config
57+
```
58+
59+
and then call the code generator:
2260

2361
```bash
24-
curl -o petstore.json https://petstore3.swagger.io/api/v3/openapi.json
25-
npx @rtk-incubator/rtk-query-codegen-openapi --hooks petstore.json > petstore-api.generated.ts
62+
npx @rtk-query/codegen-openapi openapi-config.ts
2663
```
2764

28-
We recommend placing these generated types in one file that you do not modify (so you can constantly re-generate it when your API definition changes) and creating a second file to enhance it with additional info:
65+
### Programmatic usage
2966

30-
```ts title="petstore-api.ts"
31-
// file: petstore-api.generated.ts noEmit
32-
export * from 'petstore-api.generated'
67+
```ts
68+
import { generateEndpoints } from '@rtk-query/codegen-openapi'
3369

34-
// file: petstoreApi.ts
35-
import { api as generatedApi } from './petstore-api.generated'
70+
const api = await generateEndpoints({
71+
apiFile: './fixtures/emptyApi.ts',
72+
schemaFile: resolve(__dirname, 'fixtures/petstore.json'),
73+
filterEndpoints: ['getPetById', 'addPet'],
74+
hooks: true,
75+
})
76+
```
3677

37-
export const api = generatedApi.enhanceEndpoints({
38-
addTagTypes: ['Pet'],
39-
endpoints: {
40-
// basic notation: just specify properties to be overridden
41-
getPetById: {
42-
providesTags: (result, error, arg) => [{ type: 'Pet', id: arg.petId }],
43-
},
44-
findPetsByStatus: {
45-
providesTags: (result) =>
46-
// is result available?
47-
result
48-
? // successful query
49-
[
50-
{ type: 'Pet', id: 'LIST' },
51-
...result.map((pet) => ({ type: 'Pet' as const, id: pet.id })),
52-
]
53-
: // an error occurred, but we still want to refetch this query when `{ type: 'Pet', id: 'LIST' }` is invalidated
54-
[{ type: 'Pet', id: 'LIST' }],
78+
### Config file options
79+
80+
#### Simple usage
81+
82+
```ts
83+
interface SimpleUsage {
84+
apiFile: string
85+
schemaFile: string
86+
apiImport?: string
87+
exportName?: string
88+
argSuffix?: string
89+
responseSuffix?: string
90+
hooks?: boolean
91+
outputFile: string
92+
filterEndpoints?:
93+
| string
94+
| RegExp
95+
| EndpointMatcherFunction
96+
| Array<string | RegExp | EndpointMatcherFunction>
97+
endpointOverrides?: EndpointOverrides[]
98+
}
99+
100+
export type EndpointMatcherFunction = (
101+
operationName: string,
102+
operationDefinition: OperationDefinition
103+
) => boolean
104+
```
105+
106+
#### Filtering endpoints
107+
108+
If you only want to include a few endpoints, you can use the `filterEndpoints` config option to filter your endpoints.
109+
110+
```ts
111+
const filteredConfig: ConfigFile = {
112+
// ...
113+
// should only have endpoints loginUser, placeOrder, getOrderById, deleteOrder
114+
filterEndpoints: ['loginUser', /Order/],
115+
}
116+
```
117+
118+
#### Endpoint overrides
119+
120+
If an endpoint is generated as a mutation instead of a query or the other way round, you can override that:
121+
122+
```ts
123+
const withOverride: ConfigFile = {
124+
// ...
125+
endpointOverrides: [
126+
{
127+
pattern: 'loginUser',
128+
type: 'mutation',
55129
},
56-
// alternate notation: callback that gets passed in `endpoint` - you can freely modify the object here
57-
addPet: (endpoint) => {
58-
endpoint.invalidatesTags = (result) =>
59-
result ? [{ type: 'Pet', id: result.id }] : []
130+
],
131+
}
132+
```
133+
134+
#### Multiple output files
135+
136+
```ts
137+
const config: ConfigFile = {
138+
schemaFile: 'https://petstore3.swagger.io/api/v3/openapi.json',
139+
apiFile: './src/store/emptyApi.ts',
140+
outputFiles: {
141+
'./src/store/user.js': {
142+
filterEndpoints: [/user/i],
60143
},
61-
updatePet: {
62-
invalidatesTags: (result, error, arg) => [
63-
{ type: 'Pet', id: arg.pet.id },
64-
],
144+
'./src/store/order.js': {
145+
filterEndpoints: [/order/i],
65146
},
66-
deletePet: {
67-
invalidatesTags: (result, error, arg) => [{ type: 'Pet', id: arg.petId }],
147+
'./src/store/pet.js': {
148+
filterEndpoints: [/pet/i],
68149
},
69150
},
70-
})
71-
72-
export const {
73-
useGetPetByIdQuery,
74-
useFindPetsByStatusQuery,
75-
useAddPetMutation,
76-
useUpdatePetMutation,
77-
useDeletePetMutation,
78-
} = api
151+
}
79152
```
80-
81-
## GraphQL
82-
83-
There is a _very_ early WIP PR that [implements code generation based on a GraphQL spec](https://github.com/phryneas/graphql-code-generator/pull/1), and an open issue on the GraphQL Generator repo asking [if an RTK Query generator would be potentially useful](https://github.com/dotansimha/graphql-code-generator/issues/6085).

packages/rtk-query-codegen-openapi/README.md

Lines changed: 0 additions & 120 deletions
Original file line numberDiff line numberDiff line change
@@ -15,126 +15,6 @@ Code Generator
1515

1616
This is a utility library meant to be used with [RTK Query](https://redux-toolkit.js.org/rtk-query/overview) that will generate a typed API client from an OpenAPI schema.
1717

18-
### Usage
19-
20-
Create an empty api using `createApi` like
21-
22-
```ts
23-
// Or from '@reduxjs/toolkit/query' if not using the auto-generated hooks
24-
import { createApi, fetchBaseQuery } from '@reduxjs/toolkit/query/react';
25-
26-
// initialize an empty api service that we'll inject endpoints into later as needed
27-
export const emptySplitApi = createApi({
28-
baseQuery: fetchBaseQuery({ baseUrl: '/' }),
29-
endpoints: () => ({}),
30-
});
31-
```
32-
33-
Generate a config file (json, js or ts) with contents like
34-
35-
```ts
36-
import { ConfigFile } from '@rtk-incubator/rtk-query-codegen-openapi';
37-
38-
const config: ConfigFile = {
39-
schemaFile: 'https://petstore3.swagger.io/api/v3/openapi.json',
40-
apiFile: './src/store/emptyApi.ts',
41-
apiImport: 'emptyApi',
42-
outputFile: './src/store/petApi.ts',
43-
exportName: 'petApi',
44-
hooks: true,
45-
};
46-
47-
export default config;
48-
```
49-
50-
and then call the code generator:
51-
52-
```bash
53-
npx @rtk-incubator/rtk-query-codegen-openapi openapi-config.ts
54-
```
55-
56-
### Programmatic usage
57-
58-
```ts
59-
import { generateEndpoints } from '@rtk-incubator/rtk-query-codegen-openapi';
60-
61-
const api = await generateEndpoints({
62-
apiFile: './fixtures/emptyApi.ts',
63-
schemaFile: resolve(__dirname, 'fixtures/petstore.json'),
64-
filterEndpoints: ['getPetById', 'addPet'],
65-
hooks: true,
66-
});
67-
```
68-
69-
### Config file options
70-
71-
#### Simple usage
72-
73-
```ts
74-
interface SimpleUsage {
75-
apiFile: string;
76-
schemaFile: string;
77-
apiImport?: string;
78-
exportName?: string;
79-
argSuffix?: string;
80-
responseSuffix?: string;
81-
hooks?: boolean;
82-
outputFile: string;
83-
filterEndpoints?: string | RegExp | (string | RegExp)[];
84-
endpointOverrides?: EndpointOverrides[];
85-
}
86-
```
87-
88-
#### Filtering endpoints
89-
90-
If you only want to include a few endpoints, you can use the `filterEndpoints` config option to filter your endpoints.
91-
92-
```ts
93-
const filteredConfig: ConfigFile = {
94-
// ...
95-
// should only have endpoints loginUser, placeOrder, getOrderById, deleteOrder
96-
filterEndpoints: ['loginUser', /Order/],
97-
};
98-
```
99-
100-
#### Endpoint overrides
101-
102-
If an endpoint is generated as a mutation instead of a query or the other way round, you can override that:
103-
104-
```ts
105-
const withOverride: ConfigFile = {
106-
// ...
107-
endpointOverrides: [
108-
{
109-
pattern: 'loginUser',
110-
type: 'mutation',
111-
},
112-
],
113-
};
114-
```
115-
116-
#### Multiple output files
117-
118-
```ts
119-
const config: ConfigFile = {
120-
schemaFile: 'https://petstore3.swagger.io/api/v3/openapi.json',
121-
apiFile: './src/store/emptyApi.ts',
122-
outputFiles: {
123-
'./src/store/user.js': {
124-
filterEndpoints: [/user/i],
125-
},
126-
'./src/store/order.js': {
127-
filterEndpoints: [/order/i],
128-
},
129-
'./src/store/pet.js': {
130-
filterEndpoints: [/pet/i],
131-
},
132-
},
133-
};
134-
```
135-
13618
### Documentation
13719

13820
[View the RTK Query Code Generation docs](https://redux-toolkit.js.org/rtk-query/usage/code-generation)
139-
140-
TODO these need to be updated!

0 commit comments

Comments
 (0)