Open History to see the last commit
1// eslint-disable-next-line @typescript-eslint/no-var-requires
2const createUtilsObject = require('../../utils')
3// eslint-disable-next-line @typescript-eslint/no-var-requires
4const createUseQueryLikeTransformer = require('../../utils/transformers/use-query-like-transformer')
5// eslint-disable-next-line @typescript-eslint/no-var-requires
6const createQueryClientTransformer = require('../../utils/transformers/query-client-transformer')
7// eslint-disable-next-line @typescript-eslint/no-var-requires
8const AlreadyHasPlaceholderDataProperty = require('./utils/already-has-placeholder-data-property')
9β
10/**
11 * @param {import('jscodeshift')} jscodeshift
12 * @param {Object} utils
13 * @param {import('jscodeshift').Collection} root
14 * @param {string} filePath
15 * @param {{keyName: "mutationKey"|"queryKey", queryClientMethods: ReadonlyArray<string>, hooks: ReadonlyArray<string>}} config
16 */
17const transformUsages = ({ jscodeshift, utils, root, filePath, config }) => {
18 /**
19 * @param {import('jscodeshift').CallExpression | import('jscodeshift').ExpressionStatement} node
20 * @returns {{start: number, end: number}}
21 */
22 const getNodeLocation = (node) => {
23 const location = utils.isCallExpression(node) ? node.callee.loc : node.loc
24 const start = location.start.line
25 const end = location.end.line
26β
27 return { start, end }
28 }
29β
30 /**
31 * @param {import('jscodeshift').ObjectProperty} objectProperty
32 * @returns {boolean}
33 */
34 const isKeepPreviousDataObjectProperty = (objectProperty) => {
35 return jscodeshift.match(objectProperty.key, {
36 type: jscodeshift.Identifier.name,
37 name: 'keepPreviousData',
38 })
39 }
40β
41 /**
42 * @param {import('jscodeshift').ObjectProperty} objectProperty
43 * @returns {boolean}
44 */
45 const isObjectPropertyHasTrueBooleanLiteralValue = (objectProperty) => {
46 return jscodeshift.match(objectProperty.value, {
47 type: jscodeshift.BooleanLiteral.name,
48 value: true,
49 })
50 }
51β
52 /**
53 * @param {import('jscodeshift').ObjectExpression} objectExpression
54 * @returns {Array<import('jscodeshift').ObjectProperty>}
55 */
56 const filterKeepPreviousDataProperty = (objectExpression) => {
57 return objectExpression.properties.filter((objectProperty) => {
58 return !isKeepPreviousDataObjectProperty(objectProperty)
59 })
60 }
61β
62 const createPlaceholderDataObjectProperty = () => {
63 return jscodeshift.objectProperty(
64 jscodeshift.identifier('placeholderData'),
65 jscodeshift.identifier('keepPreviousData'),
66 )
67 }
68β
69 /**
70 * @param {import('jscodeshift').ObjectExpression} objectExpression
71 * @returns {boolean}
72 */
73 const hasPlaceholderDataProperty = (objectExpression) => {
74 return (
75 objectExpression.properties.findIndex((objectProperty) => {
76 return jscodeshift.match(objectProperty.key, {
77 type: jscodeshift.Identifier.name,
78 name: 'placeholderData',
79 })
80 }) !== -1
81 )
82 }
83β
84 /**
85 * @param {import('jscodeshift').ObjectExpression} objectExpression
86 * @returns {import('jscodeshift').ObjectProperty | undefined}
87 */
88 const getKeepPreviousDataProperty = (objectExpression) => {
89 return objectExpression.properties.find(isKeepPreviousDataObjectProperty)
90 }
91β
92 let shouldAddKeepPreviousDataImport = false
93β
94 const replacer = (path, resolveTargetArgument, transformNode) => {
95 const node = path.node
96 const { start, end } = getNodeLocation(node)
97β
98 try {
99 const targetArgument = resolveTargetArgument(node)
100β
101 if (targetArgument && utils.isObjectExpression(targetArgument)) {
102 const isPlaceholderDataPropertyPresent =
103 hasPlaceholderDataProperty(targetArgument)
104β
105 if (hasPlaceholderDataProperty(targetArgument)) {
106 throw new AlreadyHasPlaceholderDataProperty(node, filePath)
107 }
108β
109 const keepPreviousDataProperty =
110 getKeepPreviousDataProperty(targetArgument)
111β
112 const keepPreviousDataPropertyHasTrueValue =
113 isObjectPropertyHasTrueBooleanLiteralValue(keepPreviousDataProperty)
114β
115 if (!keepPreviousDataPropertyHasTrueValue) {
116 utils.warn(
117 `The usage in file "${filePath}" at line ${start}:${end} already contains a "keepPreviousData" property but its value is not "true". Please migrate this usage manually.`,
118 )
119β
120 return node
121 }
122β
123 if (keepPreviousDataPropertyHasTrueValue) {
124 // Removing the `keepPreviousData` property from the object.
125 const mutableObjectExpressionProperties =
126 filterKeepPreviousDataProperty(targetArgument)
127β
128 if (!isPlaceholderDataPropertyPresent) {
129 shouldAddKeepPreviousDataImport = true
130β
131 // When the `placeholderData` property is not present, the `placeholderData: keepPreviousData` property will be added.
132 mutableObjectExpressionProperties.push(
133 createPlaceholderDataObjectProperty(),
134 )
135 }
136β
137 return transformNode(
138 node,
139 jscodeshift.objectExpression(mutableObjectExpressionProperties),
140 )
141 }
142 }
143β
144 utils.warn(
145 `The usage in file "${filePath}" at line ${start}:${end} could not be transformed, because the first parameter is not an object expression. Please migrate this usage manually.`,
146 )
147β
148 return node
149 } catch (error) {
150 utils.warn(
151 error.name === AlreadyHasPlaceholderDataProperty.name
152 ? error.message
153 : `An unknown error occurred while processing the "${filePath}" file. Please review this file, because the codemod couldn't be applied.`,
154 )
155β
156 return node
157 }
158 }
159β
160 createUseQueryLikeTransformer({ jscodeshift, utils, root }).execute(
161 config.hooks,
162 (path) => {
163 const resolveTargetArgument = (node) => node.arguments[0] ?? null
164 const transformNode = (node, transformedArgument) =>
165 jscodeshift.callExpression(node.original.callee, [transformedArgument])
166β
167 return replacer(path, resolveTargetArgument, transformNode)
168 },
169 )
170β
171 createQueryClientTransformer({ jscodeshift, utils, root }).execute(
172 config.queryClientMethods,
173 (path) => {
174 const resolveTargetArgument = (node) => node.arguments[1] ?? null
175 const transformNode = (node, transformedArgument) => {
176 return jscodeshift.callExpression(node.original.callee, [
177 node.arguments[0],
178 transformedArgument,
179 ...node.arguments.slice(2, 0),
180 ])
181 }
182β
183 return replacer(path, resolveTargetArgument, transformNode)
184 },
185 )
186β
187 const importIdentifierOfQueryClient = utils.getSelectorByImports(
188 utils.locateImports(['QueryClient']),
189 'QueryClient',
190 )
191β
192 root
193 .find(jscodeshift.ExpressionStatement, {
194 expression: {
195 type: jscodeshift.NewExpression.name,
196 callee: {
197 type: jscodeshift.Identifier.name,
198 name: importIdentifierOfQueryClient,
199 },
200 },
201 })
202 .filter((path) => path.node.expression)
203 .replaceWith((path) => {
204 const resolveTargetArgument = (node) => {
205 const paths = jscodeshift(node)
206 .find(jscodeshift.ObjectProperty, {
207 key: {
208 type: jscodeshift.Identifier.name,
209 name: 'keepPreviousData',
210 },
211 })
212 .paths()
213β
214 return paths.length > 0 ? paths[0].parent.node : null
215 }
216 const transformNode = (node, transformedArgument) => {
217 jscodeshift(node.expression)
218 .find(jscodeshift.ObjectProperty, {
219 key: {
220 type: jscodeshift.Identifier.name,
221 name: 'queries',
222 },
223 })
224 .replaceWith(({ node: mutableNode }) => {
225 mutableNode.value.properties = transformedArgument.properties
226β
227 return mutableNode
228 })
229β
230 return node
231 }
232β
233 return replacer(path, resolveTargetArgument, transformNode)
234 })
235β
236 return { shouldAddKeepPreviousDataImport }
237}
238β
239module.exports = (file, api) => {
240 const jscodeshift = api.jscodeshift
241 const root = jscodeshift(file.source)
242 const utils = createUtilsObject({ root, jscodeshift })
243 const filePath = file.path
244β
245 const dependencies = { jscodeshift, utils, root, filePath }
246β
247 const { shouldAddKeepPreviousDataImport } = transformUsages({
248 ...dependencies,
249 config: {
250 hooks: ['useInfiniteQuery', 'useQueries', 'useQuery'],
251 queryClientMethods: ['setQueryDefaults'],
252 },
253 })
254β
255 if (shouldAddKeepPreviousDataImport) {
256 root
257 .find(jscodeshift.ImportDeclaration, {
258 source: {
259 value: '@tanstack/react-query',
260 },
261 })
262 .replaceWith(({ node: mutableNode }) => {
263 mutableNode.specifiers = [
264 jscodeshift.importSpecifier(
265 jscodeshift.identifier('keepPreviousData'),
266 ),
267 ...mutableNode.specifiers,
268 ]
269β
270 return mutableNode
271 })
272 }
273β
274 return root.toSource({ quote: 'single', lineTerminator: '\n' })
275}