-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathno-return-promise-resolve.js
84 lines (83 loc) · 3.21 KB
/
no-return-promise-resolve.js
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
/** @type {import("eslint").Rule.RuleModule} */
module.exports = {
meta: {
type: "suggestion",
fixable: "code",
schema: [],
messages: {
returnResolve: `Values must be returned directly from async functions`,
returnReject: `Errors must be thrown directly from async functions`,
},
},
create(context) {
return {
[`:matches(:function[async=true] ReturnStatement, ArrowFunctionExpression[async=true]) > CallExpression > MemberExpression[object.name="Promise"][property.name=/^(resolve|reject)$/].callee`]:
/**
* @param {(
* import("estree").MemberExpression & {
* parent: import("estree").CallExpression & {
* parent: import("estree").ReturnStatement | import("estree").ArrowFunctionExpression
* }
* property: import("estree").MemberExpression["property"] & { name: string }
* }
* )} node
*/
(node) => {
// The AST selector ensures that we are somewhere within an async function, but we might
// be in a nested function that is not async. Check that the innermost function scope is
// actually async.
const functionScope = context.sourceCode.getScope(node).variableScope;
if (
functionScope.type !== "function" ||
!(
/** @type {Partial<import("estree").Function>} */ (
functionScope.block
).async
)
) {
return;
}
const sourceCode = context.getSourceCode();
const returnOrArrowFunction = node.parent.parent;
const callExpr = node.parent;
const isReturn = returnOrArrowFunction.type === "ReturnStatement";
const isArrowFunction = !isReturn;
const isReject = node.property.name === "reject";
context.report({
node: isReject && isReturn ? returnOrArrowFunction : callExpr,
messageId: isReject ? "returnReject" : "returnResolve",
fix(fixer) {
if (callExpr.arguments.length === 0) {
return fixer.replaceText(callExpr, "undefined");
}
if (isReject) {
if (isArrowFunction) {
return fixer.replaceText(
returnOrArrowFunction.body,
`{ throw ${sourceCode.getText(callExpr.arguments[0])}; }`
);
} else {
return fixer.replaceText(
returnOrArrowFunction,
`throw ${sourceCode.getText(callExpr.arguments[0])};`
);
}
}
const firstArgToken =
callExpr.arguments[0] &&
sourceCode.getFirstToken(callExpr.arguments[0]);
const needsParens =
isArrowFunction &&
firstArgToken?.type === "Punctuator" &&
firstArgToken.value === "{";
const argText = sourceCode.getText(callExpr.arguments[0]);
return fixer.replaceText(
callExpr,
needsParens ? `(${argText})` : argText
);
},
});
},
};
},
};