-
Notifications
You must be signed in to change notification settings - Fork 147
/
Copy pathawait-async-utils.ts
113 lines (102 loc) · 3.24 KB
/
await-async-utils.ts
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
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
import { TSESTree } from '@typescript-eslint/experimental-utils';
import {
findClosestCallExpressionNode,
getFunctionName,
getInnermostReturningFunction,
getVariableReferences,
isMemberExpression,
isPromiseHandled,
} from '../node-utils';
import { createTestingLibraryRule } from '../create-testing-library-rule';
export const RULE_NAME = 'await-async-utils';
export type MessageIds = 'awaitAsyncUtil' | 'asyncUtilWrapper';
type Options = [];
export default createTestingLibraryRule<Options, MessageIds>({
name: RULE_NAME,
meta: {
type: 'problem',
docs: {
description: 'Enforce promises from async utils to be handled',
category: 'Best Practices',
recommended: 'warn',
},
messages: {
awaitAsyncUtil: 'Promise returned from `{{ name }}` must be handled',
asyncUtilWrapper:
'Promise returned from {{ name }} wrapper over async util must be handled',
},
fixable: null,
schema: [],
},
defaultOptions: [],
create(context, _, helpers) {
const functionWrappersNames: string[] = [];
function detectAsyncUtilWrapper(node: TSESTree.Identifier) {
const innerFunction = getInnermostReturningFunction(context, node);
if (innerFunction) {
functionWrappersNames.push(getFunctionName(innerFunction));
}
}
return {
'CallExpression Identifier'(node: TSESTree.Identifier) {
if (helpers.isAsyncUtil(node)) {
if (
!helpers.isNodeComingFromTestingLibrary(node) &&
!(
isMemberExpression(node.parent) &&
helpers.isNodeComingFromTestingLibrary(node.parent)
)
) {
return;
}
// detect async query used within wrapper function for later analysis
detectAsyncUtilWrapper(node);
const closestCallExpression = findClosestCallExpressionNode(
node,
true
);
if (!closestCallExpression) {
return;
}
const references = getVariableReferences(
context,
closestCallExpression.parent
);
if (references && references.length === 0) {
if (!isPromiseHandled(node)) {
return context.report({
node,
messageId: 'awaitAsyncUtil',
data: {
name: node.name,
},
});
}
} else {
for (const reference of references) {
const referenceNode = reference.identifier as TSESTree.Identifier;
if (!isPromiseHandled(referenceNode)) {
return context.report({
node,
messageId: 'awaitAsyncUtil',
data: {
name: referenceNode.name,
},
});
}
}
}
} else if (functionWrappersNames.includes(node.name)) {
// check async queries used within a wrapper previously detected
if (!isPromiseHandled(node)) {
return context.report({
node,
messageId: 'asyncUtilWrapper',
data: { name: node.name },
});
}
}
},
};
},
});