We need to watch out for quite a few pitfalls when designing our architecture. One of them is the possibility of circular dependencies. In this article, we go through this concept in the context of Node.js modules and NestJS services.
Circular dependencies in Node.js modules
A circular dependency between Node.js modules happens when two files import each other. Let’s look into this straightforward example:
1const { two } = require('./two');
2
3const one = '1';
4
5console.log('file one.js:', one, two);
6
7module.exports.one = one;1const { one } = require('./one');
2
3const two = '2';
4
5console.log('file two.js:', one, two);
6
7module.exports.two = two;After running node ./one.js, we see the following output:
file two.js: undefined 2 file one.js: 1 2 (node:109498) Warning: Accessing non-existent property ‘one’ of module exports inside circular dependency (Use node --trace-warnings ... to show where the warning was created)
We can see that a code containing circular dependencies can run but might result in unexpected results. The above code executes as follows:
- one.js executes, and imports two.js,
- two.js executes, and imports one.js,
- to prevent an infinite loop, two.js loads an unfinished copy of one.js, this is why the one variable in two.js is undefined,
- two.js finishes executing, and its exported value reaches one.js,
- one.js continues running and contains all valid values.
The above example allows us to understand how Node.js reacts to circular dependencies. Circular dependencies are often a sign of a bad design, and we should avoid them when possible.
Detecting circular dependencies using ESLint
The provided code example makes it very obvious that there is a circular dependency between files. It is not always that apparent, though. Fortunately, ESLint can help us detect such dependencies. To do that, we need the eslint-plugin-import package.
1npm install eslint-plugin-importThe rule that we want is called import/no-cycle, and it ensures that no circular dependencies are present between our files.
In our NestJS project, we would set the configuration in the following way:
1module.exports = {
2 "parser": "@typescript-eslint/parser",
3 "plugins": [
4 "import",
5 // ...
6 ],
7 "extends": [
8 "plugin:import/typescript",
9 // ...
10 ],
11 "rules": {
12 "import/no-cycle": 2,
13 // ...
14 },
15 // ...
16};Circular dependencies in NestJS
Besides circular dependencies between Node.js modules, we might also run into this issue when working with NestJS modules. In part 55 of this series, we’ve implemented a feature of uploading files to the server. Let’s expand on it to create a case with a circular dependency.
1import { Injectable, NotFoundException } from '@nestjs/common';
2import { InjectRepository } from '@nestjs/typeorm';
3import { Repository } from 'typeorm';
4import LocalFile from './localFile.entity';
5import { UsersService } from '../users/users.service';
6
7@Injectable()
8class LocalFilesService {
9 constructor(
10 @InjectRepository(LocalFile)
11 private localFilesRepository: Repository<LocalFile>,
12 private usersService: UsersService
13 ) {}
14
15 async getUserAvatar(userId: number) {
16 const user = await this.usersService.getById(userId);
17 return this.getFileById(user.avatarId);
18 }
19
20 async saveLocalFileData(fileData: LocalFileDto) {
21 const newFile = await this.localFilesRepository.create(fileData)
22 await this.localFilesRepository.save(newFile);
23 return newFile;
24 }
25
26 async getFileById(fileId: number) {
27 const file = await this.localFilesRepository.findOne(fileId);
28 if (!file) {
29 throw new NotFoundException();
30 }
31 return file;
32 }
33}
34
35export default LocalFilesService;1import { HttpException, HttpStatus, Injectable } from '@nestjs/common';
2import { InjectRepository } from '@nestjs/typeorm';
3import { Repository } from 'typeorm';
4import User from './user.entity';
5import LocalFilesService from '../localFiles/localFiles.service';
6
7@Injectable()
8export class UsersService {
9 constructor(
10 @InjectRepository(User)
11 private usersRepository: Repository<User>,
12 private localFilesService: LocalFilesService
13 ) {}
14
15 async getById(id: number) {
16 const user = await this.usersRepository.findOne({ id });
17 if (user) {
18 return user;
19 }
20 throw new HttpException('User with this id does not exist', HttpStatus.NOT_FOUND);
21 }
22
23 async addAvatar(userId: number, fileData: LocalFileDto) {
24 const avatar = await this.localFilesService.saveLocalFileData(fileData);
25 await this.usersRepository.update(userId, {
26 avatarId: avatar.id
27 })
28 }
29
30 // ...
31}Solving the issue using forward referencing
In our case, the LocalFilesService needs the UsersService and the other way around. Let’s look into how our modules look so far.
1import { Module } from '@nestjs/common';
2import { TypeOrmModule } from '@nestjs/typeorm';
3import { ConfigModule } from '@nestjs/config';
4import LocalFile from './localFile.entity';
5import LocalFilesService from './localFiles.service';
6import LocalFilesController from './localFiles.controller';
7import { UsersModule } from '../users/users.module';
8
9@Module({
10 imports: [
11 TypeOrmModule.forFeature([LocalFile]),
12 ConfigModule,
13 UsersModule
14 ],
15 providers: [LocalFilesService],
16 exports: [LocalFilesService],
17 controllers: [LocalFilesController]
18})
19export class LocalFilesModule {}1import { Module } from '@nestjs/common';
2import { UsersService } from './users.service';
3import { TypeOrmModule } from '@nestjs/typeorm';
4import User from './user.entity';
5import { UsersController } from './users.controller';
6import { ConfigModule } from '@nestjs/config';
7import { LocalFilesModule } from '../localFiles/localFiles.module';
8
9@Module({
10 imports: [
11 TypeOrmModule.forFeature([User]),
12 ConfigModule,
13 LocalFilesModule,
14 // ...
15 ],
16 providers: [UsersService],
17 exports: [UsersService],
18 controllers: [UsersController]
19})
20export class UsersModule {}Above, we see that LocalFilesModule imports the UsersModule and vice versa. Running the application with the above configuration causes an error, unfortunately.
[ExceptionHandler] Nest cannot create the LocalFilesModule instance. The module at index [2] of the LocalFilesModule “imports” array is undefined. Potential causes: – A circular dependency between modules. Use forwardRef() to avoid it. Read more: https://docs.nestjs.com/fundamentals/circular-dependency – The module at index [2] is of type “undefined”. Check your import statements and the type of the module. Scope [AppModule -> PostsModule -> UsersModule] Error: Nest cannot create the LocalFilesModule instance. The module at index [2] of the LocalFilesModule “imports” array is undefined.
A workaround for the above is to use forward referencing. Thanks to it, we can refer to a module before NestJS initializes it. To do that, we need to use the forwardRef function.
1import { Module, forwardRef } from '@nestjs/common';
2import { TypeOrmModule } from '@nestjs/typeorm';
3import { ConfigModule } from '@nestjs/config';
4import LocalFile from './localFile.entity';
5import LocalFilesService from './localFiles.service';
6import LocalFilesController from './localFiles.controller';
7import { UsersModule } from '../users/users.module';
8
9@Module({
10 imports: [
11 TypeOrmModule.forFeature([LocalFile]),
12 ConfigModule,
13 forwardRef(() => UsersModule),
14 ],
15 providers: [LocalFilesService],
16 exports: [LocalFilesService],
17 controllers: [LocalFilesController]
18})
19export class LocalFilesModule {}1import { Module, forwardRef } from '@nestjs/common';
2import { UsersService } from './users.service';
3import { TypeOrmModule } from '@nestjs/typeorm';
4import User from './user.entity';
5import { UsersController } from './users.controller';
6import { ConfigModule } from '@nestjs/config';
7import { LocalFilesModule } from '../localFiles/localFiles.module';
8
9@Module({
10 imports: [
11 TypeOrmModule.forFeature([User]),
12 ConfigModule,
13 forwardRef(() => LocalFilesModule),
14 // ...
15 ],
16 providers: [UsersService],
17 exports: [UsersService],
18 controllers: [UsersController]
19})
20export class UsersModule {}Doing the above solves the issue of circular dependencies between our modules. Unfortunately, we still need to fix the problem for services. We need to use the forwardRef function and the @Inject() decorator to do that.
1import { forwardRef, Inject, Injectable } from '@nestjs/common';
2import { InjectRepository } from '@nestjs/typeorm';
3import { Repository } from 'typeorm';
4import LocalFile from './localFile.entity';
5import { UsersService } from '../users/users.service';
6
7@Injectable()
8class LocalFilesService {
9 constructor(
10 @InjectRepository(LocalFile)
11 private localFilesRepository: Repository<LocalFile>,
12 @Inject(forwardRef(() => UsersService))
13 private usersService: UsersService
14 ) {}
15
16 // ...
17}
18
19export default LocalFilesService;1import {
2 forwardRef,
3 Inject,
4 Injectable,
5} from '@nestjs/common';
6import { InjectRepository } from '@nestjs/typeorm';
7import { Repository } from 'typeorm';
8import User from './user.entity';
9import LocalFilesService from '../localFiles/localFiles.service';
10
11@Injectable()
12export class UsersService {
13 constructor(
14 @InjectRepository(User)
15 private usersRepository: Repository<User>,
16 @Inject(forwardRef(() => LocalFilesService))
17 private localFilesService: LocalFilesService
18 ) {}
19
20 // ...
21}Doing all of the above causes our services to function correctly despite the circular dependencies.
Circular dependencies between TypeORM entities
We might also run into issues with circular dependencies with TypeORM entities. For example, this might happen when dealing with relationships.
If you want to know more about relationships with TypeORM and NestJS, check out API with NestJS #7. Creating relationships with Postgres and TypeORM
Fortunately, people noticed this problem, and there is a solution. For a whole discussion, check out this issue on GitHub.
Avoiding circular dependencies in our architecture
Unfortunately, having circular dependencies in our modules is often a sign of a design worth improving. In our case, we violate the single responsibility principle of SOLID. Our LocalFilesService and UsersService are responsible for multiple functionalities.
If you want to know more about SOLID, check out Applying SOLID principles to your TypeScript code
We can create a service that encapsulates the functionalities that would otherwise cause the circular dependency issue.
1import { Injectable } from '@nestjs/common';
2import { UsersService } from '../users/users.service';
3import LocalFilesService from '../localFiles/localFiles.service';
4
5@Injectable()
6class UserAvatarsService {
7 constructor(
8 private localFilesService: LocalFilesService,
9 private usersService: UsersService
10 ) {}
11
12 async getUserAvatar(userId: number) {
13 const user = await this.usersService.getById(userId);
14 return this.localFilesService.getFileById(user.avatarId);
15 }
16
17 async addAvatar(userId: number, fileData: LocalFileDto) {
18 const avatar = await this.localFilesService.saveLocalFileData(fileData);
19 await this.usersService.updateUser(userId, {
20 avatarId: avatar.id
21 })
22 }
23}
24
25export default UserAvatarsService;We can now use the above service straight in our UsersController or create a brand new controller just for the new service.
1import { BadRequestException, Controller, Post, Req, UploadedFile, UseGuards, UseInterceptors } from '@nestjs/common';
2import JwtAuthenticationGuard from '../authentication/jwt-authentication.guard';
3import RequestWithUser from '../authentication/requestWithUser.interface';
4import { Express } from 'express';
5import LocalFilesInterceptor from '../localFiles/localFiles.interceptor';
6import { ApiBody, ApiConsumes } from '@nestjs/swagger';
7import FileUploadDto from './dto/fileUpload.dto';
8import UserAvatarsService from '../userAvatars/userAvatars.service';
9
10@Controller('users')
11export class UsersController {
12 constructor(
13 private readonly userAvatarsService: UserAvatarsService
14 ) {}
15
16 @Post('avatar')
17 @UseGuards(JwtAuthenticationGuard)
18 @UseInterceptors(LocalFilesInterceptor({
19 fieldName: 'file',
20 path: '/avatars',
21 fileFilter: (request, file, callback) => {
22 if (!file.mimetype.includes('image')) {
23 return callback(new BadRequestException('Provide a valid image'), false);
24 }
25 callback(null, true);
26 },
27 limits: {
28 fileSize: Math.pow(1024, 2) // 1MB
29 }
30 }))
31 @ApiConsumes('multipart/form-data')
32 @ApiBody({
33 description: 'A new avatar for the user',
34 type: FileUploadDto,
35 })
36 async addAvatar(@Req() request: RequestWithUser, @UploadedFile() file: Express.Multer.File) {
37 return this.userAvatarsService.addAvatar(request.user.id, {
38 path: file.path,
39 filename: file.originalname,
40 mimetype: file.mimetype
41 });
42 }
43}Summary
In this article, we’ve looked into the issue of circular dependencies in the context of Node.js and NestJS. We’ve learned how Node.js deals with circular dependencies and how it can lead to problems that might be difficult to predict. We’ve also dealt with circular dependencies across NestJS using forward referencing. Since that is just a workaround and circular dependencies can signify a lacking design, we rewrote our code to eliminate it. That is usually the best approach, and we should avoid introducing circular dependencies to our architecture.