-
Notifications
You must be signed in to change notification settings - Fork 0
feat: detect circular dependency for services #22
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
Changes from all commits
Commits
Show all changes
5 commits
Select commit
Hold shift + click to select a range
0135532
feat: detect circular dependency for services
thiagomini 6cf4043
feat: detect module circular dependency
thiagomini 730602a
refactor: remove unnecessary guard clause
thiagomini ba52a67
feat: detect circular reference recognizes import alias
thiagomini 3119d96
docs: add docs for new rule
thiagomini File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,55 @@ | ||
| --- | ||
| description: 'Detects usage of `forwardRef()` function commonly used to handle circular references' | ||
| --- | ||
|
|
||
| [Forward references](https://docs.nestjs.com/fundamentals/circular-dependency#forward-reference) are commonly used to handle circular dependencies between services or modules. For example, if `FooService` and `BarService` depend on each other, you can use `forwardRef()` to resolve the circular dependency. However, `forwardRef()` must be a last resort, and we generally recommend changing your code to avoid circular dependencies. This rule detects usage of the `forwardRef()` method so you can keep track of what potentially needs refactoring. | ||
|
|
||
| One strategy to avoid circular dependencies between services is to make each responsible for a single use case. That way you decrease the interface and likelihood of circular dependencies. You can also avoid using services as facades for data repositories. Instead, services should be usually used to encapsulate business logic (commands). Leave query responsibilities to repositories. | ||
|
|
||
| ## Options | ||
|
|
||
| This rule has no additional options yet. | ||
|
|
||
|
|
||
| ## Examples | ||
|
|
||
| ### ❌ Incorrect | ||
|
|
||
| ```ts | ||
| import { forwardRef } from '@nestjs/common'; | ||
|
|
||
| @Injectable() | ||
| export class CatsService { | ||
| constructor( | ||
| @Inject(forwardRef(() => CommonService)) // ⚠️ Circular-dependency detected | ||
| private commonService: CommonService, | ||
| ) {} | ||
| } | ||
|
|
||
| @Module({ | ||
| imports: [forwardRef(() => CatsModule)], // ⚠️ Circular-dependency detected | ||
| }) | ||
| export class FooModule {} | ||
| ``` | ||
|
|
||
| ### ✅ Correct | ||
|
|
||
| ```ts | ||
| import { forwardRef } from '@nestjs/common'; | ||
|
|
||
| @Injectable() | ||
| export class CatsService { | ||
| constructor( | ||
| private commonService: CommonService, | ||
| ) {} | ||
| } | ||
|
|
||
| @Module({ | ||
| imports: [CatsModule], | ||
| }) | ||
| export class FooModule {} | ||
| ``` | ||
|
|
||
| ## When Not To Use It | ||
|
|
||
| If your project uses `forwardRef()` extensively, you can disable this rule. | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,102 @@ | ||
| import { | ||
| AST_NODE_TYPES, | ||
| ESLintUtils, | ||
| type TSESTree, | ||
| } from '@typescript-eslint/utils'; | ||
|
|
||
| const createRule = ESLintUtils.RuleCreator( | ||
| (name) => `https://eslint.org/docs/latest/rules/${name}` | ||
| ); | ||
|
|
||
| export type MessageIds = | ||
| | 'serviceCircularDependency' | ||
| | 'moduleCircularDependency'; | ||
|
|
||
| const defaultOptions: unknown[] = []; | ||
|
|
||
| export default createRule<unknown[], MessageIds>({ | ||
| name: 'detect-circular-reference', | ||
| meta: { | ||
| type: 'problem', | ||
| docs: { | ||
| description: | ||
| 'Warns about circular dependencies with forwardRef() function', | ||
| recommended: 'recommended', | ||
| }, | ||
| fixable: undefined, | ||
| schema: [], // no options | ||
| messages: { | ||
| serviceCircularDependency: '⚠️ Circular-dependency detected', | ||
| moduleCircularDependency: '⚠️ Circular-dependency detected', | ||
| }, | ||
| }, | ||
| defaultOptions, | ||
| create(context) { | ||
| let forwardRefName: string = 'forwardRef'; | ||
| return { | ||
| 'ImportDeclaration > ImportSpecifier[imported.name="forwardRef"]': ( | ||
| node: TSESTree.ImportSpecifier & { | ||
| parent: TSESTree.ImportDeclaration; | ||
| imported: TSESTree.Identifier & { | ||
| source: TSESTree.Literal; | ||
| }; | ||
| } | ||
| ) => { | ||
| if (node.parent?.source.value === '@nestjs/common') { | ||
| forwardRefName = node.local.name; | ||
| } | ||
| }, | ||
|
|
||
| 'CallExpression > Identifier': ( | ||
| node: TSESTree.Identifier & { | ||
| parent: TSESTree.CallExpression; | ||
| } | ||
| ) => { | ||
| if (node.name !== forwardRefName) { | ||
| return; | ||
| } | ||
|
|
||
| if (isNodeWithinImportsArray(node.parent, forwardRefName)) { | ||
| return context.report({ | ||
| messageId: 'moduleCircularDependency', | ||
| node, | ||
| loc: node.loc, | ||
| }); | ||
| } | ||
|
|
||
| return context.report({ | ||
| messageId: 'serviceCircularDependency', | ||
| node, | ||
| loc: node.loc, | ||
| }); | ||
| }, | ||
| }; | ||
| }, | ||
| }); | ||
|
|
||
| function isNodeWithinImportsArray( | ||
| node: TSESTree.CallExpression, | ||
| forwardRefName: string | ||
| ): boolean { | ||
| return !!( | ||
| node.parent?.type === AST_NODE_TYPES.ArrayExpression && | ||
| node.parent?.elements.find((element) => | ||
| isForwardRefExpression(element, forwardRefName) | ||
| ) | ||
| ); | ||
| } | ||
|
|
||
| function isForwardRefExpression( | ||
| node: TSESTree.Expression | null | TSESTree.SpreadElement, | ||
| forwardRefName: string | ||
| ): node is TSESTree.CallExpression & { | ||
| callee: TSESTree.Identifier & { | ||
| name: string; | ||
| }; | ||
| } { | ||
| return ( | ||
| node?.type === AST_NODE_TYPES.CallExpression && | ||
| node?.callee.type === AST_NODE_TYPES.Identifier && | ||
| node?.callee.name === forwardRefName | ||
| ); | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,95 @@ | ||
| import { RuleTester } from '@typescript-eslint/rule-tester'; | ||
| import detectCircularReferenceRule from '../../src/rules/detect-circular-reference.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('detect-circular-reference', detectCircularReferenceRule, { | ||
| valid: [ | ||
| { | ||
| code: ` | ||
| import { forwardRef } from '@nestjs/common'; | ||
| import { CommonService } from './common.service'; | ||
| @Injectable() | ||
| export class CatsService { | ||
| constructor( | ||
| private commonService: CommonService, | ||
| ) {} | ||
| } | ||
| `, | ||
| }, | ||
| { | ||
| code: ` | ||
| @Module({ | ||
| imports: [CatsModule], | ||
| }) | ||
| export class CommonModule {} | ||
| `, | ||
| }, | ||
| ], | ||
| invalid: [ | ||
| { | ||
| code: ` | ||
| import { forwardRef } from '@nestjs/common'; | ||
|
|
||
| @Injectable() | ||
| export class CatsService { | ||
| constructor( | ||
| @Inject(forwardRef(() => CommonService)) // ⚠️ Circular-dependency detected | ||
| private commonService: CommonService, | ||
| ) {} | ||
| } | ||
| `, | ||
| errors: [ | ||
| { | ||
| messageId: 'serviceCircularDependency', | ||
| }, | ||
| ], | ||
| }, | ||
| { | ||
| code: ` | ||
| import { forwardRef as renamedForwardRef } from '@nestjs/common'; | ||
|
|
||
| @Injectable() | ||
| export class CatsService { | ||
| constructor( | ||
| @Inject(renamedForwardRef(() => CommonService)) // ⚠️ Circular-dependency detected | ||
| private commonService: CommonService, | ||
| ) {} | ||
| } | ||
| `, | ||
| errors: [ | ||
| { | ||
| messageId: 'serviceCircularDependency', | ||
| }, | ||
| ], | ||
| }, | ||
| { | ||
| code: ` | ||
| import { forwardRef } from '@nestjs/common' | ||
| @Module({ | ||
| imports: [forwardRef(() => CatsModule)], // ⚠️ Circular-dependency detected | ||
| }) | ||
| export class CommonModule {} | ||
| `, | ||
| errors: [ | ||
| { | ||
| messageId: 'moduleCircularDependency', | ||
| }, | ||
| ], | ||
| }, | ||
| ], | ||
| }); |
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
I'd be hesitant to advise detailed alternative strategies. It could easily be interpreted as the official way to structure a Nest app, whereas it's highly dependent on the context. i.e. if it's a simple REST app, entity-based module structure is appropriate, and simply splitting splitting the service would probably suffice.
If the app's primary responsibility is transforming and loading data, transaction scripts are a great fit.
Highly complex apps with lots of business logic would again require a different approach, and DDD would probably be a better fit, but that would depend on the skills within the team too 😄
I'd suggest we drop the second paragraph and just stick to the generic "we recommend refactoring the code to avoid the circular dependency" from the first paragraph 🙂
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Yeah, I think you are right; I thought of providing some direction to users who would ask themselves, "Then what should we do?", but maybe a blog post is a better way of doing it