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

no-void-query-fn.rule.ts

94 lines2.8 KB

1import { 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 { ParserServicesWithTypeInformation } from '@typescript-eslint/utils'
6import type { ExtraRuleDocs } from '../../types'
7​
8export const name = 'no-void-query-fn'
9​
10const createRule = ESLintUtils.RuleCreator<ExtraRuleDocs>(getDocsUrl)
11​
12export const rule = createRule({
13 name,
14 meta: {
15 type: 'problem',
16 docs: {
17 description: 'Ensures queryFn returns a non-undefined value',
18 recommended: 'error',
19 },
20 messages: {
21 noVoidReturn: 'queryFn must return a non-undefined value',
22 },
23 schema: [],
24 },
25 defaultOptions: [],
26​
27 create: detectTanstackQueryImports((context) => {
28 return {
29 Property(node) {
30 if (
31 !ASTUtils.isObjectExpression(node.parent) ||
32 !ASTUtils.isIdentifierWithName(node.key, 'queryFn')
33 ) {
34 return
35 }
36​
37 const parserServices = context.sourceCode.parserServices
38​
39 if (
40 !parserServices ||
41 !parserServices.esTreeNodeToTSNodeMap ||
42 !parserServices.program
43 ) {
44 return
45 }
46​
47 const checker = parserServices.program.getTypeChecker()
48 const tsNode = parserServices.esTreeNodeToTSNodeMap.get(node.value)
49 const type = checker.getTypeAtLocation(tsNode)
50​
51 // Get the return type of the function
52 if (type.getCallSignatures().length > 0) {
53 const returnType = type.getCallSignatures()[0]?.getReturnType()
54​
55 if (!returnType) {
56 return
57 }
58​
59 // Check if return type is void or undefined
60 if (isIllegalReturn(checker, returnType)) {
61 context.report({
62 node: node.value,
63 messageId: 'noVoidReturn',
64 })
65 }
66 }
67 },
68 }
69 }),
70})
71​
72type Program = ParserServicesWithTypeInformation['program']
73type TypeChecker = ReturnType<Program['getTypeChecker']>
74type Type = ReturnType<TypeChecker['getTypeAtLocation']>
75​
76/**
77 * Checks whether a query function's return type resolves to `void` or `undefined`, including in any
78 * member of a union.
79 * @param checker - The TypeScript type checker.
80 * @param type - The return type of the query function.
81 * @returns `true` if the awaited type, or a member of it, is `void` or `undefined`.
82 */
83function isIllegalReturn(checker: TypeChecker, type: Type): boolean {
84 const awaited = checker.getAwaitedType(type)
85​
86 if (!awaited) return false
87​
88 if (awaited.isUnion()) {
89 return awaited.types.some((t) => isIllegalReturn(checker, t))
90 }
91​
92 const typeString = checker.typeToString(awaited)
93 return typeString === 'void' || typeString === 'undefined'