-
Notifications
You must be signed in to change notification settings - Fork 147
/
Copy pathrender-result-naming-convention.ts
101 lines (90 loc) · 2.72 KB
/
render-result-naming-convention.ts
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
96
97
98
99
100
101
import { ESLintUtils, TSESTree } from '@typescript-eslint/experimental-utils';
import { getDocsUrl, hasTestingLibraryImportModule } from '../utils';
import {
isCallExpression,
isIdentifier,
isImportSpecifier,
isObjectPattern,
isRenderVariableDeclarator,
} from '../node-utils';
export const RULE_NAME = 'render-result-naming-convention';
const ALLOWED_VAR_NAMES = ['view', 'utils'];
const ALLOWED_VAR_NAMES_TEXT = ALLOWED_VAR_NAMES.map(
name => '`' + name + '`'
).join(', ');
export default ESLintUtils.RuleCreator(getDocsUrl)({
name: RULE_NAME,
meta: {
type: 'suggestion',
docs: {
description: 'TODO',
category: 'Best Practices',
recommended: false,
},
messages: {
invalidRenderResultName: `\`{{ varName }}\` is not a recommended name for \`render\` returned value. Instead, you should destructure it, or call it using one of the valid choices: ${ALLOWED_VAR_NAMES_TEXT}`,
},
fixable: null,
schema: [
{
type: 'object',
properties: {
renderFunctions: {
type: 'array',
},
},
},
],
},
defaultOptions: [
{
renderFunctions: [],
},
],
create(context, [options]) {
const { renderFunctions } = options;
let renderResultName: string | null = null;
let renderAlias: string | undefined;
return {
ImportDeclaration(node: TSESTree.ImportDeclaration) {
if (!hasTestingLibraryImportModule(node)) {
return;
}
const renderImport = node.specifiers.find(
node => isImportSpecifier(node) && node.imported.name === 'render'
);
if (!renderImport) {
return;
}
renderAlias = renderImport.local.name;
},
VariableDeclarator(node) {
const isValidRenderDeclarator = isRenderVariableDeclarator(node, [
...renderFunctions,
renderAlias,
]);
if (isValidRenderDeclarator && !isObjectPattern(node.id)) {
renderResultName = isIdentifier(node.id) && node.id.name;
const renderFunctionName =
isCallExpression(node.init) &&
isIdentifier(node.init.callee) &&
node.init.callee.name;
const isTestingLibraryRender =
!!renderAlias || renderFunctions.includes(renderFunctionName);
const isAllowedRenderResultName = ALLOWED_VAR_NAMES.includes(
renderResultName
);
if (isTestingLibraryRender && !isAllowedRenderResultName) {
context.report({
node,
messageId: 'invalidRenderResultName',
data: {
varName: renderResultName,
},
});
}
}
},
};
},
});