Open History to see the last commit
1import { AST_NODE_TYPES, ESLintUtils } from '@typescript-eslint/utils'
2import { ASTUtils } from '../../utils/ast-utils'
3import { detectTanstackQueryImports } from '../../utils/detect-react-query-imports'
4import { getDocsUrl } from '../../utils/get-docs-url'
5import type { TSESLint, TSESTree } from '@typescript-eslint/utils'
6import type { ExtraRuleDocs } from '../../types'
7β
8export const name = 'prefer-query-options'
9β
10const queryHooks = [
11 'useQuery',
12 'useInfiniteQuery',
13 'useSuspenseQuery',
14 'useSuspenseInfiniteQuery',
15 'usePrefetchQuery',
16 'usePrefetchInfiniteQuery',
17]
18β
19const queriesHooks = ['useQueries', 'useSuspenseQueries']
20β
21const filterHooks = ['useIsFetching']
22β
23const queryClientOptionMethods = [
24 'fetchQuery',
25 'prefetchQuery',
26 'fetchInfiniteQuery',
27 'prefetchInfiniteQuery',
28 'ensureQueryData',
29 'ensureInfiniteQueryData',
30]
31β
32const queryClientQueryKeyMethods = [
33 'getQueryData',
34 'setQueryData',
35 'getQueryState',
36 'setQueryDefaults',
37 'getQueryDefaults',
38]
39β
40const queryClientFilterMethods = [
41 'invalidateQueries',
42 'cancelQueries',
43 'refetchQueries',
44 'removeQueries',
45 'resetQueries',
46 'isFetching',
47 'getQueriesData',
48 'setQueriesData',
49]
50β
51const queryOptionsBuilders = ['queryOptions', 'infiniteQueryOptions']
52β
53const createRule = ESLintUtils.RuleCreator<ExtraRuleDocs>(getDocsUrl)
54type Helpers = {
55 isTanstackQueryImport: (node: TSESTree.Identifier) => boolean
56}
57β
58export const rule = createRule({
59 name,
60 meta: {
61 type: 'problem',
62 docs: {
63 description:
64 'Prefer using queryOptions() to co-locate queryKey and queryFn',
65 recommended: 'strict',
66 },
67 messages: {
68 preferQueryOptions:
69 'Prefer using queryOptions() or infiniteQueryOptions() to co-locate queryKey and queryFn.',
70 preferQueryOptionsQueryKey:
71 'Prefer referencing a queryKey from a queryOptions() result instead of typing it manually.',
72 },
73 schema: [],
74 },
75 defaultOptions: [],
76β
77 create: detectTanstackQueryImports((context, _, helpers) => {
78 /**
79 * Reports an object literal passed as query options that defines `queryKey` or `queryFn` inline.
80 * @param node - The argument passed as query options.
81 */
82 function reportInlineQueryOptions(node: TSESTree.Node): void {
83 if (ASTUtils.isObjectExpression(node) && hasInlineQueryOptions(node)) {
84 context.report({
85 node,
86 messageId: 'preferQueryOptions',
87 })
88 }
89 }
90β
91 /**
92 * Reports an object literal passed as query filters whose `queryKey` is an inline array.
93 * @param node - The filters node.
94 */
95 function reportInlineFilterQueryKey(node: TSESTree.Node): void {
96 if (ASTUtils.isObjectExpression(node) && hasInlineFilterQueryKey(node)) {
97 context.report({
98 node,
99 messageId: 'preferQueryOptionsQueryKey',
100 })
101 }
102 }
103β
104 return {
105 CallExpression: (node) => {
106 if (ASTUtils.isIdentifier(node.callee)) {
107 const importedName = getTanstackImportName(
108 context,
109 helpers,
110 node.callee,
111 )
112β
113 if (importedName === null) {
114 return
115 }
116β
117 if (queryOptionsBuilders.includes(importedName)) {
118 return
119 }
120β
121 const options = node.arguments[0]
122β
123 if (options === undefined) {
124 return
125 }
126β
127 if (queryHooks.includes(importedName)) {
128 reportInlineQueryOptions(options)
129 return
130 }
131β
132 if (
133 queriesHooks.includes(importedName) &&
134 ASTUtils.isObjectExpression(options)
135 ) {
136 const queries = ASTUtils.findPropertyWithIdentifierKey(
137 options.properties,
138 'queries',
139 )?.value
140β
141 if (queries !== undefined) {
142 getQueryObjects(queries).forEach((query) => {
143 reportInlineQueryOptions(query)
144 })
145 }
146β
147 return
148 }
149β
150 if (filterHooks.includes(importedName)) {
151 reportInlineFilterQueryKey(options)
152 }
153β
154 return
155 }
156β
157 if (
158 node.callee.type !== AST_NODE_TYPES.MemberExpression ||
159 !ASTUtils.isIdentifier(node.callee.property) ||
160 !isTanstackQueryClient(node.callee.object, context, helpers)
161 ) {
162 return
163 }
164β
165 const method = node.callee.property.name
166 const options = node.arguments[0]
167β
168 if (options === undefined) {
169 return
170 }
171β
172 if (queryClientOptionMethods.includes(method)) {
173 reportInlineQueryOptions(options)
174 return
175 }
176β
177 if (
178 queryClientQueryKeyMethods.includes(method) &&
179 isInlineArrayExpression(options)
180 ) {
181 context.report({
182 node: options,
183 messageId: 'preferQueryOptionsQueryKey',
184 })
185 return
186 }
187β
188 if (queryClientFilterMethods.includes(method)) {
189 reportInlineFilterQueryKey(options)
190 }
191 },
192 }
193 }),
194})
195β
196/**
197 * Checks whether an object literal defines `queryKey` or `queryFn` inline.
198 * @param node - The object literal.
199 * @returns `true` if it has a `queryKey` or `queryFn` property.
200 */
201function hasInlineQueryOptions(node: TSESTree.ObjectExpression): boolean {
202 return (
203 ASTUtils.findPropertyWithIdentifierKey(node.properties, 'queryKey') !==
204 undefined ||
205 ASTUtils.findPropertyWithIdentifierKey(node.properties, 'queryFn') !==
206 undefined
207 )
208}
209β
210/**
211 * Checks whether an object literal has a `queryKey` written as an inline array.
212 * @param node - The object literal.
213 * @returns `true` if its `queryKey` is an array literal, ignoring type assertions.
214 */
215function hasInlineFilterQueryKey(node: TSESTree.ObjectExpression): boolean {
216 const queryKey = ASTUtils.findPropertyWithIdentifierKey(
217 node.properties,
218 'queryKey',
219 )?.value
220β
221 return queryKey !== undefined && isInlineArrayExpression(queryKey)
222}
223β
224/**
225 * Checks whether a node is an array literal, ignoring type assertions.
226 * @param node - The node to check.
227 * @returns `true` if the node is an array literal.
228 */
229function isInlineArrayExpression(node: TSESTree.Node): boolean {
230 return unwrapTypeAssertions(node).type === AST_NODE_TYPES.ArrayExpression
231}
232β
233/**
234 * Collects the object literals a node can evaluate to, following function bodies, `return`
235 * statements, and conditional, logical, and sequence expressions.
236 * @param node - The node to collect from.
237 * @returns The object literals the node can evaluate to.
238 */
239function getReturnedObjectExpressions(
240 node: TSESTree.Node,
241): Array<TSESTree.ObjectExpression> {
242 if (ASTUtils.isObjectExpression(node)) {
243 return [node]
244 }
245β
246 if (
247 node.type === AST_NODE_TYPES.ArrowFunctionExpression ||
248 node.type === AST_NODE_TYPES.FunctionExpression
249 ) {
250 return getReturnedObjectExpressions(node.body)
251 }
252β
253 if (node.type === AST_NODE_TYPES.BlockStatement) {
254 return node.body.flatMap((statement) => {
255 if (
256 statement.type === AST_NODE_TYPES.ReturnStatement &&
257 statement.argument !== null
258 ) {
259 return getReturnedObjectExpressions(statement.argument)
260 }
261β
262 return []
263 })
264 }
265β
266 if (node.type === AST_NODE_TYPES.ConditionalExpression) {
267 return [
268 ...getReturnedObjectExpressions(node.consequent),
269 ...getReturnedObjectExpressions(node.alternate),
270 ]
271 }
272β
273 if (node.type === AST_NODE_TYPES.LogicalExpression) {
274 return [
275 ...getReturnedObjectExpressions(node.left),
276 ...getReturnedObjectExpressions(node.right),
277 ]
278 }
279β
280 if (node.type === AST_NODE_TYPES.SequenceExpression) {
281 return node.expressions.flatMap((expression) =>
282 getReturnedObjectExpressions(expression),
283 )
284 }
285β
286 return []
287}
288β
289/**
290 * Collects the query option objects of a `queries` array: the object literals in an array literal,
291 * or those returned by the callback of a `.map()` call.
292 * @param node - The `queries` value.
293 * @returns The query option object literals.
294 */
295function getQueryObjects(
296 node: TSESTree.Node,
297): Array<TSESTree.ObjectExpression> {
298 if (node.type === AST_NODE_TYPES.ArrayExpression) {
299 return node.elements.flatMap((element) => {
300 if (element !== null && ASTUtils.isObjectExpression(element)) {
301 return [element]
302 }
303β
304 return []
305 })
306 }
307β
308 if (
309 node.type === AST_NODE_TYPES.CallExpression &&
310 node.callee.type === AST_NODE_TYPES.MemberExpression &&
311 ASTUtils.isIdentifierWithName(node.callee.property, 'map')
312 ) {
313 const mapper = node.arguments[0]
314β
315 if (
316 mapper?.type === AST_NODE_TYPES.ArrowFunctionExpression ||
317 mapper?.type === AST_NODE_TYPES.FunctionExpression
318 ) {
319 return getReturnedObjectExpressions(mapper)
320 }
321 }
322β
323 return []
324}
325β
326/**
327 * Checks whether a node refers to a TanStack Query client, created with `useQueryClient()` or
328 * `new QueryClient()`.
329 * @param node - The node to check.
330 * @param context - The rule context, used to resolve variables.
331 * @param helpers - The helpers that check TanStack Query imports.
332 * @returns `true` if the node comes from `useQueryClient()` or `new QueryClient()`.
333 */
334function isTanstackQueryClient(
335 node: TSESTree.Node,
336 context: Readonly<TSESLint.RuleContext<string, ReadonlyArray<unknown>>>,
337 helpers: Helpers,
338): boolean {
339 const source = resolveQueryClientSource(node, context)
340β
341 if (
342 source.type === AST_NODE_TYPES.CallExpression &&
343 ASTUtils.isIdentifier(source.callee)
344 ) {
345 return (
346 getTanstackImportName(context, helpers, source.callee) ===
347 'useQueryClient'
348 )
349 }
350β
351 if (
352 source.type === AST_NODE_TYPES.NewExpression &&
353 ASTUtils.isIdentifier(source.callee)
354 ) {
355 return (
356 getTanstackImportName(context, helpers, source.callee) === 'QueryClient'
357 )
358 }
359β
360 return false
361}
362β
363/**
364 * Returns the name an identifier was imported under from TanStack Query.
365 * @param context - The rule context.
366 * @param helpers - The helpers that check TanStack Query imports.
367 * @param node - The identifier.
368 * @returns The imported name, or `null` if the identifier isn't a named TanStack Query import.
369 */
370function getTanstackImportName(
371 context: Readonly<TSESLint.RuleContext<string, ReadonlyArray<unknown>>>,
372 helpers: Helpers,
373 node: TSESTree.Identifier,
374): string | null {
375 if (!helpers.isTanstackQueryImport(node)) {
376 return null
377 }
378β
379 const definition = context.sourceCode
380 .getScope(node)
381 .references.find((reference) => reference.identifier === node)?.resolved
382 ?.defs[0]?.node
383β
384 if (
385 definition?.type !== AST_NODE_TYPES.ImportSpecifier ||
386 definition.imported.type !== AST_NODE_TYPES.Identifier
387 ) {
388 return null
389 }
390β
391 return definition.imported.name
392}
393β
394/**
395 * Follows variable references, optional chains, and type assertions from a node to the expression it
396 * comes from.
397 * @param node - The node to start from.
398 * @param context - The rule context, used to resolve variables.
399 * @returns The innermost node that can't be resolved further.
400 */
401function resolveQueryClientSource(
402 node: TSESTree.Node,
403 context: Readonly<TSESLint.RuleContext<string, ReadonlyArray<unknown>>>,
404): TSESTree.Node {
405 const visitedNodes = new Set<TSESTree.Node>()
406β
407 while (!visitedNodes.has(node)) {
408 visitedNodes.add(node)
409β
410 if (node.type === AST_NODE_TYPES.ChainExpression) {
411 node = node.expression
412 continue
413 }
414β
415 node = unwrapTypeAssertions(node)
416β
417 if (node.type !== AST_NODE_TYPES.Identifier) {
418 return node
419 }
420β
421 const expression = ASTUtils.getReferencedExpressionByIdentifier({
422 context,
423 node,
424 })
425β
426 if (expression === null) {
427 return node
428 }
429β
430 node = expression
431 }
432β
433 return node
434}
435β
436/**
437 * Removes `as`, `satisfies`, and angle-bracket type assertions around a node.
438 * @param node - The node to unwrap.
439 * @returns The node inside the type assertions.
440 */
441function unwrapTypeAssertions(node: TSESTree.Node): TSESTree.Node {
442 while (
443 node.type === AST_NODE_TYPES.TSAsExpression ||
444 node.type === AST_NODE_TYPES.TSSatisfiesExpression ||
445 node.type === AST_NODE_TYPES.TSTypeAssertion
446 ) {
447 node = node.expression
448 }
449β
450 return node
451}