-
-
Notifications
You must be signed in to change notification settings - Fork 3.8k
Expand file tree
/
Copy pathnoRestDestructuring.ts
More file actions
97 lines (79 loc) · 2.76 KB
/
noRestDestructuring.ts
File metadata and controls
97 lines (79 loc) · 2.76 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
import { createRule } from '../utils'
import type { TSESTree } from '@typescript-eslint/utils'
export const noRestDestructuring = createRule<[], 'noRestDestructuring'>({
name: 'no-rest-destructuring',
meta: {
type: 'problem',
docs: {
description: 'Disallow rest destructuring of query results',
url: 'https://tanstack.com/query/latest/docs/eslint/no-rest-destructuring',
},
messages: {
noRestDestructuring:
'Destructuring the result of a query hook with a rest parameter can cause unexpected behavior. Instead, destructure the result into a variable first, then destructure the variable.',
},
schema: [],
},
defaultOptions: [],
create(context) {
const parserServices =
context.sourceCode?.parserServices ?? context.parserServices
function isTanstackQueryResult(node: TSESTree.Node): boolean {
if (!parserServices?.hasTypeInformation) {
return false
}
const checker = parserServices.program.getTypeChecker()
const tsNode = parserServices.esTreeNodeToTSNodeMap.get(node)
if (!tsNode) return false
const type = checker.getTypeAtLocation(tsNode)
const symbol = type.symbol || type.aliasSymbol
if (!symbol) return false
const typeName = symbol.escapedName.toString()
const queryResultTypes = [
'UseQueryResult',
'UseInfiniteQueryResult',
'QueryObserverResult',
'InfiniteQueryObserverResult',
'UseBaseQueryResult',
]
if (queryResultTypes.some((t) => typeName.includes(t))) {
return true
}
const declarations = symbol.declarations || []
for (const decl of declarations) {
const fileName = decl.getSourceFile().fileName
if (fileName.includes('@tanstack') && fileName.includes('query')) {
return true
}
}
return false
}
return {
VariableDeclarator(node: TSESTree.VariableDeclarator) {
if (node.id.type !== 'ObjectPattern') return
const hasRest = node.id.properties.some(
(prop) => prop.type === 'RestElement'
)
if (!hasRest) return
const init = node.init
if (!init || init.type !== 'CallExpression') return
const callee = init.callee
let isQueryHook = false
if (callee.type === 'Identifier' && callee.name.startsWith('use')) {
const name = callee.name
if (['useQuery', 'useInfiniteQuery'].includes(name)) {
isQueryHook = true
} else if (parserServices?.hasTypeInformation) {
isQueryHook = isTanstackQueryResult(init)
}
}
if (isQueryHook) {
context.report({
node,
messageId: 'noRestDestructuring',
})
}
},
}
},
})