1 |
|
2 |
|
3 |
|
4 |
|
5 |
|
6 |
|
7 | 'use strict'
|
8 |
|
9 | const getDocsUrl = require('./lib/get-docs-url')
|
10 | const isPromise = require('./lib/is-promise')
|
11 |
|
12 | function 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 |
|
38 | module.exports = {
|
39 | meta: {
|
40 | docs: {
|
41 | url: getDocsUrl('no-return-wrap')
|
42 | },
|
43 | messages: {
|
44 | resolve: 'Avoid wrapping return values in Promise.resolve',
|
45 | reject: 'Expected throw instead of Promise.reject'
|
46 | }
|
47 | },
|
48 | create(context) {
|
49 | const options = context.options[0] || {}
|
50 | const allowReject = options.allowReject
|
51 |
|
52 | return {
|
53 | ReturnStatement(node) {
|
54 | if (isInPromise(context)) {
|
55 | if (node.argument) {
|
56 | if (node.argument.type === 'CallExpression') {
|
57 | if (node.argument.callee.type === 'MemberExpression') {
|
58 | if (node.argument.callee.object.name === 'Promise') {
|
59 | if (node.argument.callee.property.name === 'resolve') {
|
60 | context.report({ node, messageId: 'resolve' })
|
61 | } else if (
|
62 | !allowReject &&
|
63 | node.argument.callee.property.name === 'reject'
|
64 | ) {
|
65 | context.report({ node, messageId: 'reject' })
|
66 | }
|
67 | }
|
68 | }
|
69 | }
|
70 | }
|
71 | }
|
72 | }
|
73 | }
|
74 | }
|
75 | }
|