no-return-wrap.js 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  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. 'use strict'
  7. const getDocsUrl = require('./lib/get-docs-url')
  8. const isPromise = require('./lib/is-promise')
  9. const rejectMessage = 'Expected throw instead of Promise.reject'
  10. const resolveMessage = 'Avoid wrapping return values in Promise.resolve'
  11. function isInPromise(context) {
  12. const expression = context.getAncestors().filter(function(node) {
  13. return node.type === 'ExpressionStatement'
  14. })[0]
  15. return expression && expression.expression && isPromise(expression.expression)
  16. }
  17. module.exports = {
  18. meta: {
  19. docs: {
  20. url: getDocsUrl('no-return-wrap')
  21. }
  22. },
  23. create: function(context) {
  24. const options = context.options[0] || {}
  25. const allowReject = options.allowReject
  26. return {
  27. ReturnStatement: function(node) {
  28. if (isInPromise(context)) {
  29. if (node.argument) {
  30. if (node.argument.type === 'CallExpression') {
  31. if (node.argument.callee.type === 'MemberExpression') {
  32. if (node.argument.callee.object.name === 'Promise') {
  33. if (node.argument.callee.property.name === 'resolve') {
  34. context.report({ node, message: resolveMessage })
  35. } else if (
  36. !allowReject &&
  37. node.argument.callee.property.name === 'reject'
  38. ) {
  39. context.report({ node, message: rejectMessage })
  40. }
  41. }
  42. }
  43. }
  44. }
  45. }
  46. }
  47. }
  48. }
  49. }