Skip to content

Instantly share code, notes, and snippets.

@missing1984
Last active November 16, 2022 02:11
Show Gist options
  • Save missing1984/907c2b6aef0206e8944ccbaea7c4d0a9 to your computer and use it in GitHub Desktop.
Save missing1984/907c2b6aef0206e8944ccbaea7c4d0a9 to your computer and use it in GitHub Desktop.
patch query key
const { Project, SyntaxKind } = require('ts-morph');
const updateQueryKey = async (config, projectName) => {
const apiDirs = Object.keys(config)
.filter((name) => name === projectName)
.map((name) => config[name])
.map((c) => `${c.output.target}/*.ts`);
const project = new Project({
tsConfigFilePath: './tsconfig.json',
skipAddingFilesFromTsConfig: true,
});
console.log(`apiDirs`, apiDirs);
project.addSourceFilesAtPaths(apiDirs);
project.getSourceFiles().forEach((apiFile) => {
apiFile.getVariableStatements().forEach((variable) => {
const d = variable.getDeclarations()[0];
// locate QueryKey function
if (d.getName().endsWith('QueryKey')) {
const arrowFunction = d.getLastChildByKind(SyntaxKind.ArrowFunction);
const array = arrowFunction.getLastChildByKind(SyntaxKind.ArrayLiteralExpression);
array.getChildren().forEach((node) => {
if (node.getKind() === SyntaxKind.SyntaxList) {
// break elements out
const elements = node
.getFullText()
.split(',')
.map((t) => t.trim())
.filter((t) => !!t);
// split elements by path
const splitByPath = elements
.map((t) =>
t
.replaceAll('`', '')
.split('/')
.filter((t2) => !!t2),
)
.flat();
// unpack variables
const unpacks = splitByPath.map((v) => {
if (v.includes('...')) {
return v;
}
if (v.includes('$')) {
return v.replace('${', '').replace('}', '');
}
return `'${v}'`;
});
node.replaceWithText(unpacks.join(','));
}
});
}
});
});
project.saveSync();
console.log(`patched cache key generator`);
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment