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 6 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
79 changes: 79 additions & 0 deletions src/rules/check-inject-decorator.rule.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,79 @@
import { ASTUtils, ESLintUtils, type TSESTree } from '@typescript-eslint/utils';
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) {
let injectedTokenName: string | undefined;
return {
// Matches: @Inject(FOO_SERVICE)
'Decorator[expression.callee.name="Inject"]': (
node: TSESTree.Decorator
) => {
const injectedToken = (node.expression as TSESTree.CallExpression)
.arguments[0];

if (ASTUtils.isIdentifier(injectedToken)) {
injectedTokenName = injectedToken.name;
}
},

// 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;

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

const services = ESLintUtils.getParserServices(context);
const type = services.getTypeAtLocation(node);
if (
!type.isClass() &&
type.isClassOrInterface() &&
!injectedTokenName
) {
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;
}
}
120 changes: 120 additions & 0 deletions tests/rules/check-inject-decorator.spec.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,120 @@
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: `
import { FooInterface } from './foo.interface';
class BarService {
@Inject(FOO_SERVICE)
private readonly fooService: FooInterface
constructor(
private readonly fooService2: FooInterface,
) {}
}
`,
errors: [
{
messageId: 'typeIsInterface',
},
],
},
// TODO
// The scenario below might not be desirable for every class, since not every class is supposed to be injectable and hydrated by Nest DI.
// private readonly fooService: FooService; // ⚠️ Did you want to `@Inject(FooService)`?
],
});