-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmorph-query-keys.js
49 lines (40 loc) · 1.96 KB
/
morph-query-keys.js
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
import { Project, SyntaxKind } from 'ts-morph';
const NO_CHECK_COMMENT = '// @ts-nocheck';
const project = new Project({
tsConfigFilePath: './tsconfig.json',
skipAddingFilesFromTsConfig: true,
});
// Add all .ts files inside ./src (this includes index.ts, custom-instance.ts etc.)
project.addSourceFilesAtPaths(['./src/**/*.ts', '!./src/index.ts', '!./src/custom-instance.ts']);
// We will filter out all of the extra ones (index.ts, custom-instance.ts etc.) by the number of "/"
// in the full file path. I.e. the ones we wan't to keep have one extra "/"
const getNumberOfParts = (apiFile) => apiFile.getFilePath().split('/').length; // ! Requires Windows?
const maxParts = Math.max(...project.getSourceFiles().map(getNumberOfParts));
const apiName = process.argv.at(-1); // ! probably requires a recent NodeJS version
for (const apiFile of project.getSourceFiles()) {
const fullText = apiFile.getFullText();
if (!fullText.includes(NO_CHECK_COMMENT)) {
apiFile.insertStatements(0, NO_CHECK_COMMENT);
}
if (getNumberOfParts(apiFile) === maxParts) {
// get all variables used
apiFile.getVariableStatements().forEach((variable) => {
// get their declaration, multiple declarations are never used so [0] is ok
const declaration = variable.getDeclarations()[0]; // 257 (SyntaxKind.VariableDeclaration)
// locate QueryKey function
if (declaration.getName().endsWith('QueryKey')) {
// console.log(declaration);
const arrow = declaration.getLastChildByKind(SyntaxKind.ArrowFunction);
// need to get the array expression from inside the `[] as const` expression
const array = arrow
.getBody()
.getFirstChildByKind(SyntaxKind.SyntaxList)
.getFirstChildByKind(SyntaxKind.ReturnStatement)
.getFirstChildByKind(SyntaxKind.AsExpression)
.getLastChildByKind(SyntaxKind.ArrayLiteralExpression);
array.insertElement(0, `"${apiName}"`);
}
});
}
}
project.saveSync();