no-env-in-context.js 2.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  1. /**
  2. * @fileoverview disallow `context.isServer/context.isClient` in `asyncData/fetch/nuxtServerInit`
  3. * @author Xin Du <clark.duxin@gmail.com>
  4. */
  5. 'use strict'
  6. const utils = require('../utils')
  7. // ------------------------------------------------------------------------------
  8. // Rule Definition
  9. // ------------------------------------------------------------------------------
  10. module.exports = {
  11. meta: {
  12. docs: {
  13. description:
  14. 'disallow `context.isServer/context.isClient` in `asyncData/fetch/nuxtServerInit`',
  15. category: 'base'
  16. },
  17. messages: {
  18. noEnv: 'Unexpected {{env}} in {{funcName}}.'
  19. }
  20. },
  21. create (context) {
  22. // variables should be defined here
  23. const forbiddenNodes = []
  24. const options = context.options[0] || {}
  25. const ENV = ['isServer', 'isClient']
  26. const HOOKS = new Set(['asyncData', 'fetch'].concat(options.methods || []))
  27. // ----------------------------------------------------------------------
  28. // Public
  29. // ----------------------------------------------------------------------
  30. return {
  31. MemberExpression (node) {
  32. const propertyName = node.computed ? node.property.value : node.property.name
  33. if (propertyName && ENV.includes(propertyName)) {
  34. forbiddenNodes.push({ name: propertyName, node })
  35. }
  36. },
  37. ...utils.executeOnVue(context, obj => {
  38. for (const funcName of HOOKS) {
  39. const func = utils.getFunctionWithName(obj, funcName)
  40. const param = func && func.value ? func.value.params && func.value.params[0] : false
  41. if (param) {
  42. if (param.type === 'ObjectPattern') {
  43. for (const prop of param.properties) {
  44. if (prop.key && prop.key.name && ENV.includes(prop.key.name)) {
  45. context.report({
  46. node: prop,
  47. messageId: 'noEnv',
  48. data: {
  49. env: prop.key.name,
  50. funcName
  51. }
  52. })
  53. }
  54. }
  55. } else {
  56. for (const { name, node: child } of forbiddenNodes) {
  57. if (utils.isInFunction(func, child)) {
  58. if (param.name === child.object.name) {
  59. context.report({
  60. node: child,
  61. messageId: 'noEnv',
  62. data: {
  63. env: name,
  64. funcName
  65. }
  66. })
  67. }
  68. }
  69. }
  70. }
  71. }
  72. }
  73. })
  74. }
  75. }
  76. }