|
| 1 | +import { IRuleMetadata, RuleFailure } from 'tslint'; |
| 2 | +import { AbstractRule } from 'tslint/lib/rules'; |
| 3 | +import { SourceFile } from 'typescript'; |
| 4 | +import { InjectableMetadata } from './angular'; |
| 5 | +import { NgWalker } from './angular/ngWalker'; |
| 6 | + |
| 7 | +export class Rule extends AbstractRule { |
| 8 | + static readonly metadata: IRuleMetadata = { |
| 9 | + description: "Enforces classes decorated with @Injectable to use the 'providedIn' property.", |
| 10 | + options: null, |
| 11 | + optionsDescription: 'Not configurable.', |
| 12 | + rationale: "Using the 'providedIn' property makes classes decorated with @Injectable tree shakeable.", |
| 13 | + ruleName: 'use-injectable-provided-in', |
| 14 | + type: 'functionality', |
| 15 | + typescriptOnly: true |
| 16 | + }; |
| 17 | + |
| 18 | + static readonly FAILURE_STRING = "Classes decorated with @Injectable should use the 'providedIn' property"; |
| 19 | + |
| 20 | + apply(sourceFile: SourceFile): RuleFailure[] { |
| 21 | + const walker = new Walker(sourceFile, this.getOptions()); |
| 22 | + |
| 23 | + return this.applyWithWalker(walker); |
| 24 | + } |
| 25 | +} |
| 26 | + |
| 27 | +class Walker extends NgWalker { |
| 28 | + protected visitNgInjectable(metadata: InjectableMetadata): void { |
| 29 | + this.validateInjectable(metadata); |
| 30 | + super.visitNgInjectable(metadata); |
| 31 | + } |
| 32 | + |
| 33 | + private validateInjectable(metadata: InjectableMetadata): void { |
| 34 | + if (metadata.providedIn) return; |
| 35 | + |
| 36 | + this.addFailureAtNode(metadata.decorator, Rule.FAILURE_STRING); |
| 37 | + } |
| 38 | +} |
0 commit comments