Skip to content
Source
Sign inSign up
TanStack/query
Open History to see the last commit

query-client-transformer.cjs

53 lines1.6 KB

1module.exports = ({
2 jscodeshift,
3 utils,
4 root,
5 packageName = '@tanstack/react-query',
6}) => {
7 const filterQueryClientMethodCalls = (node, methods) =>
8 utils.isIdentifier(node) && methods.includes(node.name)
9​
10 const findQueryClientMethodCalls = (importIdentifiers, methods) => {
11 /**
12 * Here we collect all query client instantiations. We have to make aware of them because some method calls might
13 * be invoked on these instances.
14 */
15 const queryClientIdentifiers =
16 utils.queryClient.findQueryClientIdentifiers(importIdentifiers)
17​
18 return (
19 utils
20 // First, we need to find all method calls.
21 .findAllMethodCalls()
22 // Then we narrow the collection to `QueryClient` methods.
23 .filter((node) =>
24 filterQueryClientMethodCalls(node.value.callee.property, methods),
25 )
26 .filter((node) => {
27 const object = node.value.callee.object
28​
29 // If the method is called on a `QueryClient` instance, we keep it in the collection.
30 if (utils.isIdentifier(object)) {
31 return queryClientIdentifiers.includes(object.name)
32 }
33​
34 // If the method is called on the return value of `useQueryClient` hook, we keep it in the collection.
35 return utils.isFunctionCallOf(
36 object,
37 utils.getSelectorByImports(importIdentifiers, 'useQueryClient'),
38 )
39 })
40 )
41 }
42​
43 const execute = (methods, replacer) => {
44 findQueryClientMethodCalls(
45 utils.locateImports(['QueryClient', 'useQueryClient'], packageName),
46 methods,
47 ).replaceWith(replacer)
48 }
49​
50 return {
51 execute,
52 }