|
| 1 | +import * as ts from 'typescript'; |
| 2 | +import * as Lint from 'tslint'; |
| 3 | + |
| 4 | +/** |
| 5 | + * Rule which enforces that all queries are explicitly marked as static or non-static. |
| 6 | + * TODO(crisbeto): we can remove this once we don't support 8.0.0 anymore. |
| 7 | + */ |
| 8 | +export class Rule extends Lint.Rules.AbstractRule { |
| 9 | + apply(sourceFile: ts.SourceFile): Lint.RuleFailure[] { |
| 10 | + return this.applyWithWalker(new Walker(sourceFile, this.getOptions())); |
| 11 | + } |
| 12 | +} |
| 13 | + |
| 14 | +class Walker extends Lint.RuleWalker { |
| 15 | + visitPropertyDeclaration(node: ts.PropertyDeclaration) { |
| 16 | + const childQueryDecorator = node.decorators && node.decorators.find(decorator => { |
| 17 | + const expression = (decorator.expression as ts.CallExpression); |
| 18 | + const name = expression && expression.expression.getText(); |
| 19 | + return name === 'ViewChild' || name === 'ContentChild'; |
| 20 | + }); |
| 21 | + |
| 22 | + if (childQueryDecorator) { |
| 23 | + const options = (childQueryDecorator.expression as ts.CallExpression).arguments[1]; |
| 24 | + |
| 25 | + if (!options || !ts.isObjectLiteralExpression(options) || |
| 26 | + !this._getObjectProperty(options, 'static')) { |
| 27 | + this.addFailureAtNode(childQueryDecorator, |
| 28 | + 'Queries have to explicitly set the `static` option.'); |
| 29 | + } |
| 30 | + } |
| 31 | + |
| 32 | + super.visitPropertyDeclaration(node); |
| 33 | + } |
| 34 | + |
| 35 | + /** Gets the node of an object property by name. */ |
| 36 | + private _getObjectProperty(node: ts.ObjectLiteralExpression, name: string) { |
| 37 | + return node.properties.find(property => (property.name as ts.Identifier).getText() === name); |
| 38 | + } |
| 39 | +} |
0 commit comments