-
Notifications
You must be signed in to change notification settings - Fork 147
/
Copy pathawait-async-utils.ts
107 lines (96 loc) · 3.03 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
import { TSESTree } from '@typescript-eslint/experimental-utils';
import { createTestingLibraryRule } from '../create-testing-library-rule';
import {
findClosestCallExpressionNode,
getFunctionName,
getInnermostReturningFunction,
getVariableReferences,
isPromiseHandled,
} from '../node-utils';
export const RULE_NAME = 'await-async-utils';
export type MessageIds = 'asyncUtilWrapper' | 'awaitAsyncUtil';
type Options = [];
export default createTestingLibraryRule<Options, MessageIds>({
name: RULE_NAME,
meta: {
type: 'problem',
docs: {
description: 'Enforce promises from async utils to be awaited properly',
recommendedConfig: {
dom: 'error',
angular: 'error',
react: 'error',
vue: 'error',
},
},
messages: {
awaitAsyncUtil: 'Promise returned from `{{ name }}` must be handled',
asyncUtilWrapper:
'Promise returned from {{ name }} wrapper over async util must be handled',
},
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)) {
// detect async query used within wrapper function for later analysis
detectAsyncUtilWrapper(node);
const closestCallExpression = findClosestCallExpressionNode(
node,
true
);
if (!closestCallExpression || !closestCallExpression.parent) {
return;
}
const references = getVariableReferences(
context,
closestCallExpression.parent
);
if (references.length === 0) {
if (!isPromiseHandled(node)) {
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)) {
context.report({
node,
messageId: 'awaitAsyncUtil',
data: {
name: node.name,
},
});
return;
}
}
}
} else if (functionWrappersNames.includes(node.name)) {
// check async queries used within a wrapper previously detected
if (!isPromiseHandled(node)) {
context.report({
node,
messageId: 'asyncUtilWrapper',
data: { name: node.name },
});
}
}
},
};
},
});