require-await.js
3.17 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
98
99
100
101
102
103
104
105
106
107
108
109
/**
* @fileoverview Rule to disallow async functions which have no `await` expression.
* @author Toru Nagashima
*/
"use strict";
//------------------------------------------------------------------------------
// Requirements
//------------------------------------------------------------------------------
const astUtils = require("./utils/ast-utils");
//------------------------------------------------------------------------------
// Helpers
//------------------------------------------------------------------------------
/**
* Capitalize the 1st letter of the given text.
* @param {string} text The text to capitalize.
* @returns {string} The text that the 1st letter was capitalized.
*/
function capitalizeFirstLetter(text) {
return text[0].toUpperCase() + text.slice(1);
}
//------------------------------------------------------------------------------
// Rule Definition
//------------------------------------------------------------------------------
module.exports = {
meta: {
type: "suggestion",
docs: {
description: "disallow async functions which have no `await` expression",
category: "Best Practices",
recommended: false,
url: "https://eslint.org/docs/rules/require-await"
},
schema: []
},
create(context) {
const sourceCode = context.getSourceCode();
let scopeInfo = null;
/**
* Push the scope info object to the stack.
* @returns {void}
*/
function enterFunction() {
scopeInfo = {
upper: scopeInfo,
hasAwait: false
};
}
/**
* Pop the top scope info object from the stack.
* Also, it reports the function if needed.
* @param {ASTNode} node The node to report.
* @returns {void}
*/
function exitFunction(node) {
if (node.async && !scopeInfo.hasAwait && !astUtils.isEmptyFunction(node)) {
context.report({
node,
loc: astUtils.getFunctionHeadLoc(node, sourceCode),
message: "{{name}} has no 'await' expression.",
data: {
name: capitalizeFirstLetter(
astUtils.getFunctionNameWithKind(node)
)
}
});
}
scopeInfo = scopeInfo.upper;
}
return {
FunctionDeclaration: enterFunction,
FunctionExpression: enterFunction,
ArrowFunctionExpression: enterFunction,
"FunctionDeclaration:exit": exitFunction,
"FunctionExpression:exit": exitFunction,
"ArrowFunctionExpression:exit": exitFunction,
AwaitExpression() {
if (!scopeInfo) {
return;
}
scopeInfo.hasAwait = true;
},
ForOfStatement(node) {
if (!scopeInfo) {
return;
}
if (node.await) {
scopeInfo.hasAwait = true;
}
}
};
}
};