Skip to content

Commit 07eec30

Browse files
authored
Merge pull request #2380 from reduxjs/prepare-codegen-1.1
Codegen v1.1 integration
2 parents 37db532 + 215a73d commit 07eec30

File tree

13 files changed

+1185
-413
lines changed

13 files changed

+1185
-413
lines changed

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

Lines changed: 17 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -62,6 +62,15 @@ and then call the code generator:
6262
npx @rtk-query/codegen-openapi openapi-config.ts
6363
```
6464

65+
#### Generating tags
66+
67+
If your OpenAPI specification uses [tags](https://swagger.io/docs/specification/grouping-operations-with-tags/), you can specify the `tag` option to the codegen.
68+
That will result in all generated endpoints having `providesTags`/`invalidatesTags` declarations for the `tags` of their respective operation definition.
69+
70+
Note that this will only result in string tags with no ids, so it might lead to scenarios where too much is invalidated and unneccessary requests are made on mutation.
71+
72+
In that case it is still recommended to manually specify tags by using [`enhanceEndpoints`](./code-splitting.mdx) on top of the generated api and manually declare `providesTags`/`invalidatesTags`.
73+
6574
### Programmatic usage
6675

6776
```ts no-transpile title="src/store/petApi.ts"
@@ -87,7 +96,10 @@ interface SimpleUsage {
8796
exportName?: string
8897
argSuffix?: string
8998
responseSuffix?: string
90-
hooks?: boolean
99+
hooks?:
100+
| boolean
101+
| { queries: boolean; lazyQueries: boolean; mutations: boolean }
102+
tag?: boolean
91103
outputFile: string
92104
filterEndpoints?:
93105
| string
@@ -131,6 +143,10 @@ const withOverride: ConfigFile = {
131143
}
132144
```
133145

146+
#### Generating hooks
147+
148+
Setting `hooks: true` will generate `useQuery` and `useMuation` hook exports. If you also want `useLazyQuery` hooks generated or more granular control, you can also pass an object in the shape of: `{ queries: boolean; lazyQueries: boolean; mutations: boolean }`.
149+
134150
#### Multiple output files
135151

136152
```ts no-transpile title="openapi-config.ts"

packages/rtk-query-codegen-openapi/package.json

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -56,8 +56,8 @@
5656
},
5757
"dependencies": {
5858
"@apidevtools/swagger-parser": "^10.0.2",
59+
"@rtk-query/oazapfts-patched": "^3.6.0-2",
5960
"commander": "^6.2.0",
60-
"oazapfts": "^3.5.0",
6161
"prettier": "^2.2.1",
6262
"semver": "^7.3.5",
6363
"swagger2openapi": "^7.0.4",

packages/rtk-query-codegen-openapi/src/bin/cli.ts

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -43,7 +43,7 @@ program.version(meta.version).usage('</path/to/config.js>').parse(process.argv);
4343

4444
const configFile = program.args[0];
4545

46-
if (program.args.length === 0 || !/\.(jsx?|tsx?|jsonc?)?$/.test(configFile)) {
46+
if (program.args.length === 0 || !/\.(c?(jsx?|tsx?)|jsonc?)?$/.test(configFile)) {
4747
program.help();
4848
} else {
4949
if (/\.tsx?$/.test(configFile) && !ts) {

packages/rtk-query-codegen-openapi/src/codegen.ts

Lines changed: 99 additions & 29 deletions
Original file line numberDiff line numberDiff line change
@@ -3,9 +3,11 @@ import { factory } from './utils/factory';
33

44
const defaultEndpointBuilder = factory.createIdentifier('build');
55

6-
export type ObjectPropertyDefinitions = Record<string, ts.Expression>;
6+
export type ObjectPropertyDefinitions = Record<string, ts.Expression | undefined>;
77
export function generateObjectProperties(obj: ObjectPropertyDefinitions) {
8-
return Object.entries(obj).map(([k, v]) => factory.createPropertyAssignment(factory.createIdentifier(k), v));
8+
return Object.entries(obj)
9+
.filter(([_, v]) => v)
10+
.map(([k, v]) => factory.createPropertyAssignment(factory.createIdentifier(k), v as ts.Expression));
911
}
1012

1113
export function generateImportNode(pkg: string, namedImports: Record<string, string>, defaultImportName?: string) {
@@ -31,10 +33,69 @@ export function generateImportNode(pkg: string, namedImports: Record<string, str
3133
export function generateCreateApiCall({
3234
endpointBuilder = defaultEndpointBuilder,
3335
endpointDefinitions,
36+
tag,
3437
}: {
3538
endpointBuilder?: ts.Identifier;
3639
endpointDefinitions: ts.ObjectLiteralExpression;
40+
tag: boolean;
3741
}) {
42+
const injectEndpointsObjectLiteralExpression = factory.createObjectLiteralExpression(
43+
generateObjectProperties({
44+
endpoints: factory.createArrowFunction(
45+
undefined,
46+
undefined,
47+
[
48+
factory.createParameterDeclaration(
49+
undefined,
50+
undefined,
51+
undefined,
52+
endpointBuilder,
53+
undefined,
54+
undefined,
55+
undefined
56+
),
57+
],
58+
undefined,
59+
factory.createToken(ts.SyntaxKind.EqualsGreaterThanToken),
60+
factory.createParenthesizedExpression(endpointDefinitions)
61+
),
62+
overrideExisting: factory.createFalse(),
63+
}),
64+
true
65+
);
66+
if (tag) {
67+
const enhanceEndpointsObjectLiteralExpression = factory.createObjectLiteralExpression(
68+
[factory.createShorthandPropertyAssignment(factory.createIdentifier('addTagTypes'), undefined)],
69+
true
70+
)
71+
return factory.createVariableStatement(
72+
undefined,
73+
factory.createVariableDeclarationList(
74+
[factory.createVariableDeclaration(
75+
factory.createIdentifier("injectedRtkApi"),
76+
undefined,
77+
undefined,
78+
factory.createCallExpression(
79+
factory.createPropertyAccessExpression(
80+
factory.createCallExpression(
81+
factory.createPropertyAccessExpression(
82+
factory.createIdentifier("api"),
83+
factory.createIdentifier("enhanceEndpoints")
84+
),
85+
undefined,
86+
[enhanceEndpointsObjectLiteralExpression]
87+
),
88+
factory.createIdentifier("injectEndpoints")
89+
),
90+
undefined,
91+
[injectEndpointsObjectLiteralExpression]
92+
)
93+
)],
94+
ts.NodeFlags.Const
95+
)
96+
);
97+
}
98+
3899
return factory.createVariableStatement(
39100
undefined,
40101
factory.createVariableDeclarationList(
@@ -49,32 +110,7 @@ export function generateCreateApiCall({
49110
factory.createIdentifier('injectEndpoints')
50111
),
51112
undefined,
52-
[
53-
factory.createObjectLiteralExpression(
54-
generateObjectProperties({
55-
endpoints: factory.createArrowFunction(
56-
undefined,
57-
undefined,
58-
[
59-
factory.createParameterDeclaration(
60-
undefined,
61-
undefined,
62-
undefined,
63-
endpointBuilder,
64-
undefined,
65-
undefined,
66-
undefined
67-
),
68-
],
69-
undefined,
70-
factory.createToken(ts.SyntaxKind.EqualsGreaterThanToken),
71-
factory.createParenthesizedExpression(endpointDefinitions)
72-
),
73-
overrideExisting: factory.createFalse(),
74-
}),
75-
true
76-
),
77-
]
113+
[injectEndpointsObjectLiteralExpression]
78114
)
79115
),
80116
],
@@ -91,6 +127,7 @@ export function generateEndpointDefinition({
91127
queryFn,
92128
endpointBuilder = defaultEndpointBuilder,
93129
extraEndpointsProps,
130+
tags,
94131
}: {
95132
operationName: string;
96133
type: 'query' | 'mutation';
@@ -99,7 +136,17 @@ export function generateEndpointDefinition({
99136
queryFn: ts.Expression;
100137
endpointBuilder?: ts.Identifier;
101138
extraEndpointsProps: ObjectPropertyDefinitions;
139+
tags: string[];
102140
}) {
141+
const objectProperties = generateObjectProperties({ query: queryFn, ...extraEndpointsProps });
142+
if (tags.length > 0) {
143+
objectProperties.push(
144+
factory.createPropertyAssignment(
145+
factory.createIdentifier(type === 'query' ? 'providesTags' : 'invalidatesTags'),
146+
factory.createArrayLiteralExpression(tags.map((tag) => factory.createStringLiteral(tag), false))
147+
)
148+
)
149+
}
103150
return factory.createPropertyAssignment(
104151
factory.createIdentifier(operationName),
105152

@@ -108,10 +155,33 @@ export function generateEndpointDefinition({
108155
[Response, QueryArg],
109156
[
110157
factory.createObjectLiteralExpression(
111-
generateObjectProperties({ query: queryFn, ...extraEndpointsProps }),
158+
objectProperties,
112159
true
113160
),
114161
]
162+
),
163+
);
164+
}
165+
166+
export function generateTagTypes({ addTagTypes }: { addTagTypes: string[] }) {
167+
return factory.createVariableStatement(
168+
[factory.createModifier(ts.SyntaxKind.ExportKeyword)],
169+
factory.createVariableDeclarationList(
170+
[
171+
factory.createVariableDeclaration(
172+
factory.createIdentifier('addTagTypes'),
173+
undefined,
174+
undefined,
175+
factory.createAsExpression(
176+
factory.createArrayLiteralExpression(
177+
addTagTypes.map((tagType) => factory.createStringLiteral(tagType)),
178+
true
179+
),
180+
factory.createTypeReferenceNode(factory.createIdentifier('const'), undefined)
181+
)
182+
),
183+
],
184+
ts.NodeFlags.Const
115185
)
116186
);
117187
}

0 commit comments

Comments
 (0)