UNPKG

2.58 kBJavaScriptView Raw
1/**
2 * Rule: no-return-wrap function
3 * Prevents unnecessary wrapping of results in Promise.resolve
4 * or Promise.reject as the Promise will do that for us
5 */
6
7'use strict'
8
9const getDocsUrl = require('./lib/get-docs-url')
10const isPromise = require('./lib/is-promise')
11
12function isInPromise(context) {
13 let functionNode = context
14 .getAncestors()
15 .filter((node) => {
16 return (
17 node.type === 'ArrowFunctionExpression' ||
18 node.type === 'FunctionExpression'
19 )
20 })
21 .reverse()[0]
22 while (
23 functionNode &&
24 functionNode.parent &&
25 functionNode.parent.type === 'MemberExpression' &&
26 functionNode.parent.object === functionNode &&
27 functionNode.parent.property.type === 'Identifier' &&
28 functionNode.parent.property.name === 'bind' &&
29 functionNode.parent.parent &&
30 functionNode.parent.parent.type === 'CallExpression' &&
31 functionNode.parent.parent.callee === functionNode.parent
32 ) {
33 functionNode = functionNode.parent.parent
34 }
35 return functionNode && functionNode.parent && isPromise(functionNode.parent)
36}
37
38module.exports = {
39 meta: {
40 type: 'suggestion',
41 docs: {
42 url: getDocsUrl('no-return-wrap'),
43 },
44 messages: {
45 resolve: 'Avoid wrapping return values in Promise.resolve',
46 reject: 'Expected throw instead of Promise.reject',
47 },
48 schema: [
49 {
50 type: 'object',
51 properties: {
52 allowReject: {
53 type: 'boolean',
54 },
55 },
56 additionalProperties: false,
57 },
58 ],
59 },
60 create(context) {
61 const options = context.options[0] || {}
62 const allowReject = options.allowReject
63
64 /**
65 * Checks a call expression, reporting if necessary.
66 * @param callExpression The call expression.
67 * @param node The node to report.
68 */
69 function checkCallExpression({ callee }, node) {
70 if (
71 isInPromise(context) &&
72 callee.type === 'MemberExpression' &&
73 callee.object.name === 'Promise'
74 ) {
75 if (callee.property.name === 'resolve') {
76 context.report({ node, messageId: 'resolve' })
77 } else if (!allowReject && callee.property.name === 'reject') {
78 context.report({ node, messageId: 'reject' })
79 }
80 }
81 }
82
83 return {
84 ReturnStatement(node) {
85 if (node.argument && node.argument.type === 'CallExpression') {
86 checkCallExpression(node.argument, node)
87 }
88 },
89 'ArrowFunctionExpression > CallExpression'(node) {
90 checkCallExpression(node, node)
91 },
92 }
93 },
94}