Skip to content

Commit 4163a76

Browse files
authored
Move RTK-Query OpenAPI Codegen into Monorepo, @rtk-query/[email protected]
2 parents 8feda19 + 7c6fb02 commit 4163a76

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

49 files changed

+7701
-112
lines changed

.codesandbox/ci.json

+4-2
Original file line numberDiff line numberDiff line change
@@ -11,11 +11,13 @@
1111
"packages": [
1212
"packages/toolkit",
1313
"packages/rtk-query-graphql-request-base-query",
14-
"packages/action-listener-middleware"
14+
"packages/action-listener-middleware",
15+
"packages/rtk-query-codegen-openapi"
1516
],
1617
"publishDirectory": {
1718
"@reduxjs/toolkit": "packages/toolkit",
1819
"@rtk-query/graphql-request-base-query": "packages/rtk-query-graphql-request-base-query",
19-
"@rtk-incubator/action-listener-middleware": "packages/action-listener-middleware"
20+
"@rtk-incubator/action-listener-middleware": "packages/action-listener-middleware",
21+
"@rtk-query/codegen-openapi": "packages/rtk-query-codegen-openapi"
2022
}
2123
}

.github/workflows/test-codegen.yml

+45
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,45 @@
1+
# This workflow will do a clean install of node dependencies, build the source code and run tests across different versions of node
2+
# For more information see: https://help.github.com/actions/language-and-framework-guides/using-nodejs-with-github-actions
3+
4+
name: RTK-Query OpenAPI Codegen Tests
5+
defaults:
6+
run:
7+
working-directory: ./packages/rtk-query-codegen-openapi
8+
9+
on: [push, pull_request]
10+
11+
jobs:
12+
changes:
13+
name: Check for changes
14+
runs-on: ubuntu-latest
15+
outputs:
16+
codegen: ${{ steps.filter.outputs.codegen }}
17+
steps:
18+
- uses: actions/checkout@v2
19+
- uses: dorny/paths-filter@v2
20+
id: filter
21+
with:
22+
filters: |
23+
codegen:
24+
- 'packages/rtk-query-codegen-openapi/**'
25+
26+
build:
27+
needs: changes
28+
if: ${{ needs.changes.outputs.codegen == 'true' }}
29+
30+
runs-on: ubuntu-latest
31+
32+
strategy:
33+
matrix:
34+
node-version: [12.x]
35+
36+
steps:
37+
- uses: actions/checkout@v2
38+
- name: Use Node.js ${{ matrix.node-version }}
39+
uses: actions/setup-node@v2
40+
with:
41+
node-version: ${{ matrix.node }}
42+
cache: 'yarn'
43+
44+
- run: yarn install
45+
- run: yarn test

.github/workflows/tests.yml

+17
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,24 @@ defaults:
55
working-directory: ./packages/toolkit
66

77
jobs:
8+
changes:
9+
name: Check for changes
10+
runs-on: ubuntu-latest
11+
outputs:
12+
toolkit: ${{ steps.filter.outputs.toolkit }}
13+
steps:
14+
- uses: actions/checkout@v2
15+
- uses: dorny/paths-filter@v2
16+
id: filter
17+
with:
18+
filters: |
19+
toolkit:
20+
- 'packages/toolkit/**'
21+
822
build:
23+
needs: changes
24+
if: ${{ needs.changes.outputs.toolkit == 'true' }}
25+
926
name: Lint, Test, Build & Pack on Node ${{ matrix.node }}
1027

1128
runs-on: ubuntu-latest

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

+120-51
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 no-transpile
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 no-transpile
45+
import { ConfigFile } from '@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 no-transpile
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 no-transpile
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 no-transpile
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 no-transpile
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 no-transpile
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/action-listener-middleware/tsconfig.base.json

+1-2
Original file line numberDiff line numberDiff line change
@@ -30,7 +30,6 @@
3030
"allowSyntheticDefaultImports": true,
3131
"emitDeclarationOnly": true,
3232
"baseUrl": ".",
33-
"paths": {
34-
}
33+
"paths": {}
3534
}
3635
}

packages/action-listener-middleware/tsconfig.json

+3-8
Original file line numberDiff line numberDiff line change
@@ -3,11 +3,6 @@
33
"compilerOptions": {
44
"outDir": "dist"
55
},
6-
"include": [
7-
"src"
8-
],
9-
"exclude": [
10-
"src/**/*.test.ts*",
11-
"src/**/tests/*"
12-
]
13-
}
6+
"include": ["src"],
7+
"exclude": ["src/**/*.test.ts*", "src/**/tests/*"]
8+
}

0 commit comments

Comments
 (0)