forked from 7nohe/openapi-react-query-codegen
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcommon.mts
More file actions
371 lines (336 loc) · 10.6 KB
/
common.mts
File metadata and controls
371 lines (336 loc) · 10.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
import type { PathLike } from "node:fs";
import { stat } from "node:fs/promises";
import path from "node:path";
import type {
ClassDeclaration,
ParameterDeclaration,
SourceFile,
Type,
VariableDeclaration,
} from "ts-morph";
import { ArrowFunction } from "ts-morph";
import ts from "typescript";
import type { LimitedUserConfig } from "./cli.mjs";
import { queriesOutputPath, requestsOutputPath } from "./constants.mjs";
export const TData = ts.factory.createIdentifier("TData");
export const TError = ts.factory.createIdentifier("TError");
export const TContext = ts.factory.createIdentifier("TContext");
export const EqualsOrGreaterThanToken = ts.factory.createToken(
ts.SyntaxKind.EqualsGreaterThanToken,
);
export const QuestionToken = ts.factory.createToken(
ts.SyntaxKind.QuestionToken,
);
export const queryKeyGenericType =
ts.factory.createTypeReferenceNode("TQueryKey");
export const queryKeyConstraint = ts.factory.createTypeReferenceNode("Array", [
ts.factory.createKeywordTypeNode(ts.SyntaxKind.UnknownKeyword),
]);
export const capitalizeFirstLetter = (str: string) => {
return str.charAt(0).toUpperCase() + str.slice(1);
};
export const lowercaseFirstLetter = (str: string) => {
return str.charAt(0).toLowerCase() + str.slice(1);
};
export const getVariableArrowFunctionParameters = (
variable: VariableDeclaration,
) => {
const initializer = variable.getInitializer();
if (!initializer) {
throw new Error("Initializer not found");
}
if (!ArrowFunction.isArrowFunction(initializer)) {
throw new Error("Initializer is not an arrow function");
}
return initializer.getParameters();
};
export const getNameFromVariable = (variable: VariableDeclaration) => {
const variableName = variable.getName();
if (!variableName) {
throw new Error("Variable name not found");
}
return variableName;
};
export type FunctionDescription = {
node: SourceFile;
method: VariableDeclaration;
methodBlock?: ts.Block;
httpMethodName: string;
jsDoc: string;
isDeprecated: boolean;
};
export async function exists(f: PathLike) {
try {
await stat(f);
return true;
} catch {
return false;
}
}
const Common = "Common";
/**
* Build a common type name by prepending the Common namespace.
*/
export function BuildCommonTypeName(name: string | ts.Identifier) {
if (typeof name === "string") {
return ts.factory.createIdentifier(`${Common}.${name}`);
}
return ts.factory.createIdentifier(`${Common}.${name.text}`);
}
/**
* Safely parse a value into a number. Checks for NaN and Infinity.
* Returns NaN if the string is not a valid number.
* @param value The value to parse.
* @returns The parsed number or NaN if the value is not a valid number.
*/
export function safeParseNumber(value: unknown): number {
const parsed = Number(value);
if (!Number.isNaN(parsed) && Number.isFinite(parsed)) {
return parsed;
}
return Number.NaN;
}
export function extractPropertiesFromObjectParam(param: ParameterDeclaration) {
const referenced = param.findReferences()[0];
const def = referenced.getDefinition();
const paramNodes = def
.getNode()
.getType()
.getProperties()
.filter((prop) => prop.getValueDeclaration()?.getType())
.map((prop) => {
return {
name: prop.getName(),
optional: prop.isOptional(),
type: prop.getValueDeclaration()?.getType(),
};
});
return paramNodes;
}
/**
* Replace the import("...") surrounding the type if there is one.
* This can happen when the type is imported from another file, but
* we are already importing all the types from that file.
*
* https://regex101.com/r/3DyHaQ/1
*
* TODO: Replace with a more robust solution.
*/
export function getShortType(type: string) {
return type.replaceAll(/import\(".*?"\)\./g, "");
}
export function getClassesFromService(node: SourceFile) {
const klasses = node.getClasses();
if (!klasses.length) {
throw new Error("No classes found");
}
return klasses.map((klass) => {
const className = klass.getName();
if (!className) {
throw new Error("Class name not found");
}
return {
className,
klass,
};
});
}
export function getClassNameFromClassNode(klass: ClassDeclaration) {
const className = klass.getName();
if (!className) {
throw new Error("Class name not found");
}
return className;
}
export function formatOptions(options: LimitedUserConfig) {
// loop through properties on the options object
// if the property is a string of number then convert it to a number
// if the property is a string of boolean then convert it to a boolean
const formattedOptions = Object.entries(options).reduce(
(acc, [key, value]) => {
const typedKey = key as keyof LimitedUserConfig;
const typedValue = value as (typeof options)[keyof LimitedUserConfig];
const parsedNumber = safeParseNumber(typedValue);
if (value === "true" || value === true) {
(acc as unknown as Record<string, boolean>)[typedKey] = true;
} else if (value === "false" || value === false) {
(acc as unknown as Record<string, boolean>)[typedKey] = false;
} else if (!Number.isNaN(parsedNumber)) {
(acc as unknown as Record<string, number>)[typedKey] = parsedNumber;
} else {
(
acc as unknown as Record<
string,
string | number | undefined | boolean
>
)[typedKey] = typedValue;
}
return acc;
},
options,
);
return formattedOptions;
}
export function buildRequestsOutputPath(outputPath: string) {
return path.join(outputPath, requestsOutputPath);
}
export function buildQueriesOutputPath(outputPath: string) {
return path.join(outputPath, queriesOutputPath);
}
export function getQueryKeyFnName(queryKey: string) {
return `${capitalizeFirstLetter(queryKey)}Fn`;
}
/**
* Create QueryKey/MutationKey exports
*/
export function createQueryKeyExport({
methodName,
queryKey,
}: {
methodName: string;
queryKey: string;
}) {
return ts.factory.createVariableStatement(
[ts.factory.createModifier(ts.SyntaxKind.ExportKeyword)],
ts.factory.createVariableDeclarationList(
[
ts.factory.createVariableDeclaration(
ts.factory.createIdentifier(queryKey),
undefined,
undefined,
ts.factory.createStringLiteral(
`${capitalizeFirstLetter(methodName)}`,
),
),
],
ts.NodeFlags.Const,
),
);
}
export function createQueryKeyFnExport(
queryKey: string,
method: VariableDeclaration,
type: "query" | "mutation" = "query",
modelNames: string[] = [],
) {
// Mutation keys don't require clientOptions
const params =
type === "query"
? getRequestParamFromMethod(method, undefined, modelNames)
: null;
// override key is used to allow the user to override the the queryKey values
const overrideKey = ts.factory.createParameterDeclaration(
undefined,
undefined,
ts.factory.createIdentifier(type === "query" ? "queryKey" : "mutationKey"),
QuestionToken,
ts.factory.createTypeReferenceNode("Array<unknown>", []),
);
return ts.factory.createVariableStatement(
[ts.factory.createModifier(ts.SyntaxKind.ExportKeyword)],
ts.factory.createVariableDeclarationList(
[
ts.factory.createVariableDeclaration(
ts.factory.createIdentifier(getQueryKeyFnName(queryKey)),
undefined,
undefined,
ts.factory.createArrowFunction(
undefined,
undefined,
params ? [params, overrideKey] : [overrideKey],
undefined,
EqualsOrGreaterThanToken,
type === "query"
? queryKeyFn(queryKey, method)
: mutationKeyFn(queryKey),
),
),
],
ts.NodeFlags.Const,
),
);
}
function queryKeyFn(
queryKey: string,
method: VariableDeclaration,
): ts.Expression {
return ts.factory.createArrayLiteralExpression(
[
ts.factory.createIdentifier(queryKey),
ts.factory.createSpreadElement(
ts.factory.createParenthesizedExpression(
ts.factory.createBinaryExpression(
ts.factory.createIdentifier("queryKey"),
ts.factory.createToken(ts.SyntaxKind.QuestionQuestionToken),
getVariableArrowFunctionParameters(method)
? // [...clientOptions]
ts.factory.createArrayLiteralExpression([
ts.factory.createIdentifier("clientOptions"),
])
: // []
ts.factory.createArrayLiteralExpression(),
),
),
),
],
false,
);
}
function mutationKeyFn(mutationKey: string): ts.Expression {
return ts.factory.createArrayLiteralExpression(
[
ts.factory.createIdentifier(mutationKey),
ts.factory.createSpreadElement(
ts.factory.createParenthesizedExpression(
ts.factory.createBinaryExpression(
ts.factory.createIdentifier("mutationKey"),
ts.factory.createToken(ts.SyntaxKind.QuestionQuestionToken),
ts.factory.createArrayLiteralExpression(),
),
),
),
],
false,
);
}
export function getRequestParamFromMethod(
method: VariableDeclaration,
pageParam?: string,
modelNames: string[] = [],
) {
if (!getVariableArrowFunctionParameters(method).length) {
return null;
}
const methodName = getNameFromVariable(method);
const params = getVariableArrowFunctionParameters(method).flatMap((param) => {
const paramNodes = extractPropertiesFromObjectParam(param);
return paramNodes
.filter((p) => p.name !== pageParam)
.map((refParam) => ({
name: refParam.name,
// TODO: Client<Request, Response, unknown, RequestOptions> -> Client<Request, Response, unknown>
typeName: getShortType(refParam.type?.getText() ?? ""),
optional: refParam.optional,
}));
});
const areAllPropertiesOptional = params.every((param) => param.optional);
return ts.factory.createParameterDeclaration(
undefined,
undefined,
ts.factory.createIdentifier("clientOptions"),
undefined,
ts.factory.createTypeReferenceNode(ts.factory.createIdentifier("Options"), [
ts.factory.createTypeReferenceNode(
modelNames.includes(`${capitalizeFirstLetter(methodName)}Data`)
? `${capitalizeFirstLetter(methodName)}Data`
: "unknown",
),
ts.factory.createTypeReferenceNode(ts.factory.createIdentifier("true")),
]),
// if all params are optional, we create an empty object literal
// so the hook can be called without any parameters
areAllPropertiesOptional
? ts.factory.createObjectLiteralExpression()
: undefined,
);
}