Skip to content

feat: rule warns when token duplicates type #12

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 14 commits into from
Jan 16, 2024
Merged
Show file tree
Hide file tree
Changes from 10 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
27 changes: 14 additions & 13 deletions docs/rules/enforce-close-testing-module.md
Original file line number Diff line number Diff line change
Expand Up @@ -15,15 +15,16 @@ This rule accepts an object with two properties: `createAliases` and `closeAlias

```json
{
"nestjs/close-testing-modules": ["error", {
"createAliases": [
{ "kind": "function", "name": "customCreateTestingModule" },
{ "kind": "method", "name": "alternativeCreateMethod" }
],
"closeAliases": [
{ "kind": "method", "name": "customCloseMethod" }
]
}]
"nestjs/close-testing-modules": [
"error",
{
"createAliases": [
{ "kind": "function", "name": "customCreateTestingModule" },
{ "kind": "method", "name": "alternativeCreateMethod" }
],
"closeAliases": [{ "kind": "method", "name": "customCloseMethod" }]
}
]
}
```

Expand Down Expand Up @@ -106,7 +107,7 @@ describe('Creates and closes the appModule using custom functions', () => {
let app: INestApplication;
beforeEach(async () => {
// defined via the "createAliases" option as { kind: 'function', name: 'createTestingModule' }
const testingModule = await createTestingModule();
const testingModule = await createTestingModule();
app = testingModule.createNestApplication();
});

Expand All @@ -116,15 +117,15 @@ describe('Creates and closes the appModule using custom functions', () => {

afterEach(async () => {
// defined via the "closeAliases" option as { kind: 'function', name: 'closeTestingModule' }
await closeTestingModule(testingModule);
await closeTestingModule(testingModule);
});
});

describe('Creates and closes the appModule using custom methods', () => {
let app: INestApplication;
beforeEach(async () => {
// defined via the "createAliases" option as { kind: 'method', name: 'createTestingModule' }
const testingModule = await testUtils.createTestingModule();
const testingModule = await testUtils.createTestingModule();
app = testingModule.createNestApplication();
});

Expand All @@ -134,7 +135,7 @@ describe('Creates and closes the appModule using custom methods', () => {

afterEach(async () => {
// defined via the "closeAliases" option as { kind: 'method', name: 'close' }
await testUtils.close(testingModule);
await testUtils.close(testingModule);
});
});
```
Expand Down
21 changes: 20 additions & 1 deletion src/ast-traverser.util.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import type { TSESTree } from '@typescript-eslint/utils';
import { AST_NODE_TYPES } from '@typescript-eslint/utils';
import { ASTUtils, AST_NODE_TYPES } from '@typescript-eslint/utils';

export function getAllParentNodesOfType<TNode extends TSESTree.Node>(
node: TSESTree.Node,
Expand Down Expand Up @@ -55,3 +55,22 @@ export function firstAssignmentExpressionInParentChain(
AST_NODE_TYPES.AssignmentExpression
);
}

export function injectDecoratorFor(node: TSESTree.Node) {
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🌽 Corn: Non-blocking, stylistic preference or nitpick

My feedback is categorized into one of five levels:

  • 🌱 Non-blocking, question
  • 🌽 Corn: Non-blocking, stylistic preference or nitpick
  • 🥚 Egg: Non-blocking, future consideration
  • 🐤 Chick: Non-blocking, requires future action
  • 🐔 Chicken: Blocking
  • 🦕 Dinosaur: Blocking, requires immediate action

See https://www.swyx.io/writing/feedback-ladders/

Can we rename this function to suggest that it returns the @Inject decorator. Now the name suggests that it injects a given decorator, so I was already looking for a second parameter 😄

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Ohh, good catch, I didn't notice that 'inject' could read as a verb here haha

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Done ✅

return (node as TSESTree.TSParameterProperty)?.decorators?.find(
(decorator) =>
decorator.expression.type === AST_NODE_TYPES.CallExpression &&
ASTUtils.isIdentifier(decorator.expression.callee) &&
decorator.expression.callee.name === 'Inject'
);
}

export function injectedTokenFor(decoratorNode?: TSESTree.Decorator) {
const injectedIdentifier = (
decoratorNode?.expression as TSESTree.CallExpression
)?.arguments[0];

const injectedToken = (injectedIdentifier as TSESTree.Identifier)?.name;

return injectedToken;
}
68 changes: 68 additions & 0 deletions src/rules/check-inject-decorator.rule.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,68 @@
import { ASTUtils, ESLintUtils, type TSESTree } from '@typescript-eslint/utils';
import * as traverser from '../ast-traverser.util';

const createRule = ESLintUtils.RuleCreator(
(name) => `https://eslint.org/docs/latest/rules/${name}`
);

export type MessageIds =
| 'tokenDuplicatesType'
| 'typeIsInterface'
| 'propertyMissingInject';

const defaultOptions: unknown[] = [];

export default createRule({
name: 'check-inject-decorator',
meta: {
type: 'problem',
docs: {
description: 'Ensure proper use of the @Inject decorator',
recommended: 'recommended',
},
fixable: undefined,
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Making this rule fixable in some cases would be nice too, @tuxmachine - but probably a work for another issue, since it's a bit harder to do it

schema: [], // no options
messages: {
tokenDuplicatesType: '⚠️ Token duplicates type',
typeIsInterface: '⚠️ Type is an interface and cannot be injected',
propertyMissingInject: '⚠️ Did you want to `@Inject({{type}})`?',
},
},
defaultOptions,
create(context) {
return {
// Matches: constructor(@Inject(FOO_SERVICE) private readonly >>fooService<<: FooService)
'TSParameterProperty > Identifier[typeAnnotation.typeAnnotation.type="TSTypeReference"]':
(node: TSESTree.Identifier) => {
const typeName = (
node.typeAnnotation?.typeAnnotation as TSESTree.TSTypeReference
).typeName;

const injectDecorator = traverser.injectDecoratorFor(node.parent);
const injectedToken = traverser.injectedTokenFor(injectDecorator);

if (
ASTUtils.isIdentifier(typeName) &&
typeName.name === injectedToken
) {
context.report({
node,
messageId: 'tokenDuplicatesType',
loc: node.loc,
});
}

const services = ESLintUtils.getParserServices(context);
const type = services.getTypeAtLocation(node);

if (!type.isClass() && type.isClassOrInterface() && !injectedToken) {
context.report({
node,
messageId: 'typeIsInterface',
loc: node.loc,
});
}
},
};
},
});
2 changes: 1 addition & 1 deletion src/rules/enforce-close-testing-module.rule.ts
Original file line number Diff line number Diff line change
Expand Up @@ -329,4 +329,4 @@ function beforeHookContainingNode(
result = callExpressionWithHook.callee.name as TestBeforeHooks;
}
return result;
}
}
117 changes: 117 additions & 0 deletions tests/rules/check-inject-decorator.spec.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,117 @@
import { RuleTester } from '@typescript-eslint/rule-tester';
import checkInjectDecorator from '../../src/rules/check-inject-decorator.rule';

// This test required changes to the tsconfig file to allow importing from the rule-tester package.
// See https://github.com/typescript-eslint/typescript-eslint/issues/7284

const ruleTester = new RuleTester({
parserOptions: {
project: './tsconfig.json',
},
parser: '@typescript-eslint/parser',
defaultFilenames: {
// We need to specify a filename that will be used by the rule parser.
// Since the test process starts at the root of the project, we need to point to the sub folder containing it.
ts: './tests/rules/file.ts',
tsx: '',
},
});

ruleTester.run('check-inject-decorator', checkInjectDecorator, {
valid: [
{
code: `
const FOO_SERVICE = Symbol('FOO_SERVICE');
class FooBarController {
constructor(
@Inject(FOO_SERVICE)
private readonly fooService: FooService,
) {}
}
`,
},
{
code: `
class FooClass {
foo: string;
}
class FooBarController {
constructor(
private readonly fooService: FooClass,
) {}
}
`,
},
{
code: `
class FooService {
@Inject(Reflector)
private readonly reflector: Reflector;
}
`,
},
{
code: `
import { INTERFACE_TOKEN } from './foo.interface.provider';
interface FooInterface { }
class FooService {
constructor(
@Inject(INTERFACE_TOKEN)
private readonly secondInterface: FooInterface
) {}
}
`,
},
],
invalid: [
{
code: `
class FooBarController {
constructor(
@Inject(BazService) // ⚠️ Token duplicates type
private readonly bazService: BazService,
) {}
}
`,
errors: [
{
messageId: 'tokenDuplicatesType',
},
],
},
{
code: `
interface FooInterface {
foo: string;
}
class FooBarController {
constructor(
private readonly fooService: FooInterface,
) {}
}
`,
errors: [
{
messageId: 'typeIsInterface',
},
],
},
{
code: `
interface FooInterface { };
class BarService {
@Inject(FOO_SERVICE)
private readonly fooService: FooInterface
constructor(
private readonly fooService2: FooInterface,
) {}
}
`,
errors: [
{
messageId: 'typeIsInterface',
},
],
},
],
});