-
Notifications
You must be signed in to change notification settings - Fork 234
/
noLifecycleCallRule.ts
49 lines (39 loc) · 1.59 KB
/
noLifecycleCallRule.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
import { IRuleMetadata, RuleFailure } from 'tslint';
import { AbstractRule } from 'tslint/lib/rules';
import { CallExpression, isPropertyAccessExpression, SourceFile, SyntaxKind } from 'typescript';
import { NgWalker } from './angular/ngWalker';
import { isLifecycleMethod } from './util/utils';
export class Rule extends AbstractRule {
static readonly metadata: IRuleMetadata = {
description: 'Disallows explicit calls to lifecycle methods.',
options: null,
optionsDescription: 'Not configurable.',
rationale: "Explicit calls to lifecycle methods could be confusing. Invoke them is an Angular's responsability.",
ruleName: 'no-lifecycle-call',
type: 'functionality',
typescriptOnly: true
};
static readonly FAILURE_STRING = 'Avoid explicit calls to lifecycle methods';
apply(sourceFile: SourceFile): RuleFailure[] {
const walker = new Walker(sourceFile, this.getOptions());
return this.applyWithWalker(walker);
}
}
class Walker extends NgWalker {
visitCallExpression(node: CallExpression): void {
this.validateCallExpression(node);
super.visitCallExpression(node);
}
private validateCallExpression(node: CallExpression): void {
const { expression: nodeExpression } = node;
if (!isPropertyAccessExpression(nodeExpression)) return;
const {
expression,
name: { text: methodName }
} = nodeExpression;
const isLifecycleCall = isLifecycleMethod(methodName);
const isSuperCall = expression.kind === SyntaxKind.SuperKeyword;
if (!isLifecycleCall || isSuperCall) return;
this.addFailureAtNode(node, Rule.FAILURE_STRING);
}
}