/
no-this-in-before-route-enter.js
95 lines (85 loc) · 2.4 KB
/
no-this-in-before-route-enter.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
/**
* @fileoverview Don't use this in a beforeRouteEnter method
* @author Przemyslaw Jan Beigert
*/
'use strict'
//------------------------------------------------------------------------------
// Rule Definition
//------------------------------------------------------------------------------
const utils = require('../utils')
;('use strict')
/**
* @param {FunctionExpression | BlockStatement | Property | ThisExpression} obj
* @returns {boolean}
*/
function deepFindThisExpression(obj) {
if (typeof obj !== 'object' || !obj) {
return false
}
if (obj.type === 'ThisExpression') {
return true
}
/** @param {typeof obj} key */
return Object.entries(obj).some(([key, value]) => {
if (key === 'parent') {
return false
}
if (Array.isArray(value)) {
return value.some((item) => deepFindThisExpression(item))
}
if (typeof value === 'object') {
return deepFindThisExpression(value)
}
return false
})
}
/**
* @param {Property | SpreadElement} property
* @returns {property is Property}
*/
function isPropertyBeforeRouteMethod(property) {
if (property.type !== 'Property') {
return false
}
return (
property.key.type === 'Identifier' &&
property.key.name === 'beforeRouteEnter'
)
}
const errorMessage =
'beforeRouteEnter does NOT have access to `this` component instance. https://router.vuejs.org/guide/advanced/navigation-guards.html#in-component-guards'
module.exports = {
errorMessage,
meta: {
type: 'suggestion',
docs: {
description: 'disallow this usage in a beforeRouteEnter method',
categories: null,
url: 'https://eslint.vuejs.org/rules/no-this-in-before-route-enter.html'
},
schema: []
},
/** @param {RuleContext} context */
create(context) {
// ----------------------------------------------------------------------
// Public
// ----------------------------------------------------------------------
return utils.executeOnVue(context, (obj) => {
const beforeRouteProperty = obj.properties.find(
isPropertyBeforeRouteMethod
)
if (!beforeRouteProperty) {
return
}
if (beforeRouteProperty.value.type !== 'FunctionExpression') {
return
}
if (deepFindThisExpression(beforeRouteProperty.value.body)) {
context.report({
node: beforeRouteProperty,
message: errorMessage
})
}
})
}
}