Open History to see the last commit
1import { AST_NODE_TYPES } from '@typescript-eslint/utils'
2import { createRule } from '../../utils/create-rule'
3import { ASTUtils } from '../../utils/ast-utils'
4import { objectKeys } from '../../utils/object-utils'
5import type { TSESLint, TSESTree } from '@typescript-eslint/utils'
6β
7const QUERY_CALLS = {
8 useQuery: { key: 'queryKey', fn: 'queryFn', type: 'query' },
9 createQuery: { key: 'queryKey', fn: 'queryFn', type: 'query' },
10 useMutation: { key: 'mutationKey', fn: 'mutationFn', type: 'mutation' },
11 createMutation: { key: 'mutationKey', fn: 'mutationFn', type: 'mutation' },
12}
13β
14const messages = {
15 preferObjectSyntax: `Objects syntax for query is preferred`,
16 returnTypeAreNotObjectSyntax: `Return type of query should be object syntax. Got {{returnType}} instead`,
17}
18β
19type MessageKey = keyof typeof messages
20β
21export const name = 'prefer-query-object-syntax'
22β
23export const rule: TSESLint.RuleModule<MessageKey, readonly unknown[]> =
24 createRule({
25 name,
26 meta: {
27 type: 'problem',
28 docs: {
29 description: 'Prefer object syntax for useQuery',
30 recommended: 'error',
31 },
32 messages: messages,
33 fixable: 'code',
34 schema: [],
35 },
36 defaultOptions: [],
37β
38 create(context, _, helpers) {
39 return {
40 CallExpression(node) {
41 if (
42 !ASTUtils.isIdentifierWithOneOfNames(
43 node.callee,
44 objectKeys(QUERY_CALLS),
45 ) ||
46 !helpers.isTanstackQueryImport(node.callee)
47 ) {
48 return
49 }
50β
51 const firstArgument = node.arguments[0]
52β
53 if (!firstArgument) {
54 return
55 }
56β
57 if (
58 node.arguments.length === 1 &&
59 firstArgument.type === AST_NODE_TYPES.CallExpression
60 ) {
61 const referencedCallExpression =
62 ASTUtils.getReferencedExpressionByIdentifier({
63 context,
64 node: firstArgument.callee,
65 })
66β
67 if (
68 referencedCallExpression === null ||
69 !ASTUtils.isNodeOfOneOf(referencedCallExpression, [
70 AST_NODE_TYPES.ArrowFunctionExpression,
71 AST_NODE_TYPES.FunctionExpression,
72 ])
73 ) {
74 return
75 }
76β
77 if (
78 !ASTUtils.isNodeOfOneOf(referencedCallExpression.body, [
79 AST_NODE_TYPES.BlockStatement,
80 AST_NODE_TYPES.ObjectExpression,
81 ])
82 ) {
83 return context.report({
84 node,
85 messageId: 'returnTypeAreNotObjectSyntax',
86 data: {
87 returnType: context
88 .getSourceCode()
89 .getText(referencedCallExpression.body),
90 },
91 })
92 }
93β
94 const returnStmts = ASTUtils.getNestedReturnStatements(
95 referencedCallExpression,
96 )
97β
98 for (const stmt of returnStmts) {
99 if (stmt.argument === null) {
100 return context.report({
101 node,
102 messageId: 'returnTypeAreNotObjectSyntax',
103 data: {
104 returnType: 'void',
105 },
106 })
107 }
108β
109 runCheckOnNode({
110 context: context,
111 callNode: node,
112 callString: node.callee.name,
113 expression: stmt.argument,
114 messageId: 'returnTypeAreNotObjectSyntax',
115 })
116 }
117β
118 return
119 }
120β
121 if (firstArgument.type === AST_NODE_TYPES.Identifier) {
122 const referencedNode = ASTUtils.getReferencedExpressionByIdentifier(
123 {
124 context,
125 node: firstArgument,
126 },
127 )
128β
129 if (referencedNode?.type === AST_NODE_TYPES.ObjectExpression) {
130 return runCheckOnNode({
131 context: context,
132 callNode: node,
133 callString: node.callee.name,
134 expression: referencedNode,
135 messageId: 'preferObjectSyntax',
136 })
137 }
138 }
139β
140 runCheckOnNode({
141 context: context,
142 callNode: node,
143 callString: node.callee.name,
144 expression: firstArgument,
145 messageId: 'preferObjectSyntax',
146 })
147 },
148 }
149 },
150 })
151β
152function runCheckOnNode(params: {
153 context: Readonly<TSESLint.RuleContext<MessageKey, readonly unknown[]>>
154 callNode: TSESTree.CallExpression
155 callString: keyof typeof QUERY_CALLS
156 expression: TSESTree.Node
157 messageId: MessageKey
158}) {
159 const { context, expression, messageId, callNode, callString } = params
160 const sourceCode = context.getSourceCode()
161β
162 if (expression.type === AST_NODE_TYPES.ObjectExpression) {
163 return
164 }
165β
166 const secondArgument = callNode.arguments[1]
167 const thirdArgument = callNode.arguments[2]
168β
169 const optionsObject =
170 secondArgument?.type === AST_NODE_TYPES.ObjectExpression
171 ? secondArgument
172 : thirdArgument !== undefined &&
173 ASTUtils.isNodeOfOneOf(thirdArgument, [
174 AST_NODE_TYPES.ObjectExpression,
175 AST_NODE_TYPES.Identifier,
176 ])
177 ? thirdArgument
178 : undefined
179β
180 if (
181 secondArgument &&
182 !thirdArgument &&
183 secondArgument !== optionsObject &&
184 secondArgument.type === AST_NODE_TYPES.Identifier
185 ) {
186 // Unable to determine if the secondArgument identifier is the options object or query fn.
187 // User has to fix the code manually.
188 context.report({ node: callNode, messageId: messageId })
189 return
190 }
191β
192 if (messageId === 'returnTypeAreNotObjectSyntax') {
193 context.report({
194 node: callNode,
195 messageId: 'returnTypeAreNotObjectSyntax',
196 data: {
197 returnType: sourceCode.getText(expression),
198 },
199 })
200 return
201 }
202β
203 const callProps = QUERY_CALLS[callString]
204β
205 context.report({
206 node: callNode,
207 messageId: 'preferObjectSyntax',
208 fix(fixer) {
209 const optionsObjectProperties: string[] = []
210β
211 if (callProps.type === 'query') {
212 // queryKey
213 const firstArgument = callNode.arguments[0]
214 const queryKey = sourceCode.getText(firstArgument)
215 const queryKeyProperty =
216 queryKey === callProps.key
217 ? callProps.key
218 : `${callProps.key}: ${queryKey}`
219β
220 optionsObjectProperties.push(queryKeyProperty)
221β
222 // queryFn
223 if (secondArgument && secondArgument !== optionsObject) {
224 const queryFn = sourceCode.getText(secondArgument)
225 const queryFnProperty =
226 queryFn === callProps.fn
227 ? callProps.fn
228 : `${callProps.fn}: ${queryFn}`
229β
230 optionsObjectProperties.push(queryFnProperty)
231 }
232 }
233β
234 if (callProps.type === 'mutation') {
235 const isMutationKeyPresent =
236 callNode.arguments.length === 3 ||
237 callNode.arguments[1]?.type === 'ArrowFunctionExpression'
238β
239 if (isMutationKeyPresent) {
240 const mutationKeyNode = callNode.arguments[0]
241 const mutationKeyText = sourceCode.getText(mutationKeyNode)
242 const mutationKeyProperty =
243 mutationKeyText === callProps.key
244 ? callProps.key
245 : `${callProps.key}: ${mutationKeyText}`
246β
247 optionsObjectProperties.push(mutationKeyProperty)
248 }
249β
250 const mutationFnNode = callNode.arguments[isMutationKeyPresent ? 1 : 0]
251 const mutationFnText = sourceCode.getText(mutationFnNode)
252 const mutationFnProperty =
253 mutationFnText === callProps.fn
254 ? callProps.fn
255 : `${callProps.fn}: ${mutationFnText}`
256β
257 optionsObjectProperties.push(mutationFnProperty)
258 }
259β
260 // options
261 if (optionsObject?.type === AST_NODE_TYPES.ObjectExpression) {
262 const existingObjectProperties = optionsObject.properties.map(
263 (objectLiteral) => {
264 return sourceCode.getText(objectLiteral)
265 },
266 )
267β
268 optionsObjectProperties.push(...existingObjectProperties)
269 }
270β
271 if (optionsObject?.type === AST_NODE_TYPES.Identifier) {
272 optionsObjectProperties.push(`...${sourceCode.getText(optionsObject)}`)
273 }
274β
275 const calleeText = sourceCode.getText(callNode).split('(')[0]
276 const argsText = `{ ${optionsObjectProperties.join(', ')} }`
277β
278 return fixer.replaceText(callNode, `${calleeText}(${argsText})`)
279 },
280 })
281}