UNPKG

1.63 kBJavaScriptView Raw
1/**
2 * Rule: no-return-wrap function
3 * Prevents uneccessary 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 const expression = context
14 .getAncestors()
15 .filter(node => node.type === 'ExpressionStatement')[0]
16 return expression && expression.expression && isPromise(expression.expression)
17}
18
19module.exports = {
20 meta: {
21 docs: {
22 url: getDocsUrl('no-return-wrap')
23 },
24 messages: {
25 resolve: 'Avoid wrapping return values in Promise.resolve',
26 reject: 'Expected throw instead of Promise.reject'
27 }
28 },
29 create(context) {
30 const options = context.options[0] || {}
31 const allowReject = options.allowReject
32
33 return {
34 ReturnStatement(node) {
35 if (isInPromise(context)) {
36 if (node.argument) {
37 if (node.argument.type === 'CallExpression') {
38 if (node.argument.callee.type === 'MemberExpression') {
39 if (node.argument.callee.object.name === 'Promise') {
40 if (node.argument.callee.property.name === 'resolve') {
41 context.report({ node, messageId: 'resolve' })
42 } else if (
43 !allowReject &&
44 node.argument.callee.property.name === 'reject'
45 ) {
46 context.report({ node, messageId: 'reject' })
47 }
48 }
49 }
50 }
51 }
52 }
53 }
54 }
55 }
56}