Dealing with circular dependencies
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…
February 28, 2022
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:
one.js#
const { two } = require('./two');
const one = '1';
console.log('file one.js:', one, two);
module.exports.one = one;two.js#
const { one } = require('./one');
const two = '2';
console.log('file two.js:', one, two);
module.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
(Usenode --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.jsexecutes, and importstwo.js,two.jsexecutes, and importsone.js,- to prevent an infinite loop,
two.jsloads an unfinished copy ofone.js,- this is why the
onevariable intwo.jsis undefined,
- this is why the
two.jsfinishes executing, and its exported value reachesone.js,one.jscontinues 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.
npm 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:
.eslintrc.js#
module.exports = {
"parser": "@typescript-eslint/parser",
"plugins": [
"import",
// ...
],
"extends": [
"plugin:import/typescript",
// ...
],
"rules": {
"import/no-cycle": 2,
// ...
},
// ...
};Circular dependencies in NestJS#
Besides circular dependencies between Node.js modules, we might also run into this issue when working with NestJS modules. Previously, we’ve implemented a feature of uploading files to the server. Let’s expand on it to create a case with a circular dependency.
localFiles.service.js#
import { Injectable, NotFoundException } from "@nestjs/common"
import { InjectRepository } from "@nestjs/typeorm"
import { Repository } from "typeorm"
import LocalFile from "./localFile.entity"
import { UsersService } from "../users/users.service"
@Injectable()
class LocalFilesService {
constructor(
@InjectRepository(LocalFile)
private localFilesRepository: Repository<LocalFile>,
private usersService: UsersService,
) {}
async getUserAvatar(userId: number) {
const user = await this.usersService.getById(userId)
return this.getFileById(user.avatarId)
}
async saveLocalFileData(fileData: LocalFileDto) {
const newFile = await this.localFilesRepository.create(fileData)
await this.localFilesRepository.save(newFile)
return newFile
}
async getFileById(fileId: number) {
const file = await this.localFilesRepository.findOne(fileId)
if (!file) {
throw new NotFoundException()
}
return file
}
}
export default LocalFilesServiceusers.service.js#
import { HttpException, HttpStatus, Injectable } from "@nestjs/common"
import { InjectRepository } from "@nestjs/typeorm"
import { Repository } from "typeorm"
import User from "./user.entity"
import LocalFilesService from "../localFiles/localFiles.service"
@Injectable()
export class UsersService {
constructor(
@InjectRepository(User)
private usersRepository: Repository<User>,
private localFilesService: LocalFilesService,
) {}
async getById(id: number) {
const user = await this.usersRepository.findOne({ id })
if (user) {
return user
}
throw new HttpException("User with this id does not exist", HttpStatus.NOT_FOUND)
}
async addAvatar(userId: number, fileData: LocalFileDto) {
const avatar = await this.localFilesService.saveLocalFileData(fileData)
await this.usersRepository.update(userId, {
avatarId: avatar.id,
})
} // ...
}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.
localFiles.module.ts#
import { Module } from "@nestjs/common"
import { TypeOrmModule } from "@nestjs/typeorm"
import { ConfigModule } from "@nestjs/config"
import LocalFile from "./localFile.entity"
import LocalFilesService from "./localFiles.service"
import LocalFilesController from "./localFiles.controller"
import { UsersModule } from "../users/users.module"
@Module({
imports: [TypeOrmModule.forFeature([LocalFile]), ConfigModule, UsersModule],
providers: [LocalFilesService],
exports: [LocalFilesService],
controllers: [LocalFilesController],
})
export class LocalFilesModule {}users.module.ts#
import { Module } from "@nestjs/common"
import { UsersService } from "./users.service"
import { TypeOrmModule } from "@nestjs/typeorm"
import User from "./user.entity"
import { UsersController } from "./users.controller"
import { ConfigModule } from "@nestjs/config"
import { LocalFilesModule } from "../localFiles/localFiles.module"
@Module({
imports: [
TypeOrmModule.forFeature([User]),
ConfigModule,
LocalFilesModule, // ...
],
providers: [UsersService],
exports: [UsersService],
controllers: [UsersController],
})
export 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.
localFiles.module.ts#
import { Module, forwardRef } from "@nestjs/common"
import { TypeOrmModule } from "@nestjs/typeorm"
import { ConfigModule } from "@nestjs/config"
import LocalFile from "./localFile.entity"
import LocalFilesService from "./localFiles.service"
import LocalFilesController from "./localFiles.controller"
import { UsersModule } from "../users/users.module"
@Module({
imports: [TypeOrmModule.forFeature([LocalFile]), ConfigModule, forwardRef(() => UsersModule)],
providers: [LocalFilesService],
exports: [LocalFilesService],
controllers: [LocalFilesController],
})
export class LocalFilesModule {}users.module.ts#
import { Module, forwardRef } from "@nestjs/common"
import { UsersService } from "./users.service"
import { TypeOrmModule } from "@nestjs/typeorm"
import User from "./user.entity"
import { UsersController } from "./users.controller"
import { ConfigModule } from "@nestjs/config"
import { LocalFilesModule } from "../localFiles/localFiles.module"
@Module({
imports: [
TypeOrmModule.forFeature([User]),
ConfigModule,
forwardRef(() => LocalFilesModule), // ...
],
providers: [UsersService],
exports: [UsersService],
controllers: [UsersController],
})
export 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.
localFiles.service.ts#
import { forwardRef, Inject, Injectable } from "@nestjs/common"
import { InjectRepository } from "@nestjs/typeorm"
import { Repository } from "typeorm"
import LocalFile from "./localFile.entity"
import { UsersService } from "../users/users.service"
@Injectable()
class LocalFilesService {
constructor(
@InjectRepository(LocalFile)
private localFilesRepository: Repository<LocalFile>,
@Inject(forwardRef(() => UsersService))
private usersService: UsersService,
) {} // ...
}
export default LocalFilesServiceusers.service.ts#
import { forwardRef, Inject, Injectable } from "@nestjs/common"
import { InjectRepository } from "@nestjs/typeorm"
import { Repository } from "typeorm"
import User from "./user.entity"
import LocalFilesService from "../localFiles/localFiles.service"
@Injectable()
export class UsersService {
constructor(
@InjectRepository(User)
private usersRepository: Repository<User>,
@Inject(forwardRef(() => LocalFilesService))
private localFilesService: LocalFilesService,
) {} // ...
}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.
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.
We can create a service that encapsulates the functionalities that would otherwise cause the circular dependency issue.
userAvatars.service.ts#
import { Injectable } from "@nestjs/common"
import { UsersService } from "../users/users.service"
import LocalFilesService from "../localFiles/localFiles.service"
@Injectable()
class UserAvatarsService {
constructor(
private localFilesService: LocalFilesService,
private usersService: UsersService,
) {}
async getUserAvatar(userId: number) {
const user = await this.usersService.getById(userId)
return this.localFilesService.getFileById(user.avatarId)
}
async addAvatar(userId: number, fileData: LocalFileDto) {
const avatar = await this.localFilesService.saveLocalFileData(fileData)
await this.usersService.updateUser(userId, {
avatarId: avatar.id,
})
}
}
export default UserAvatarsServiceWe can now use the above service straight in our UsersController or create a brand new controller just for the new service.
users.controller.ts#
import {
BadRequestException,
Controller,
Post,
Req,
UploadedFile,
UseGuards,
UseInterceptors,
} from "@nestjs/common"
import JwtAuthenticationGuard from "../authentication/jwt-authentication.guard"
import RequestWithUser from "../authentication/requestWithUser.interface"
import { Express } from "express"
import LocalFilesInterceptor from "../localFiles/localFiles.interceptor"
import { ApiBody, ApiConsumes } from "@nestjs/swagger"
import FileUploadDto from "./dto/fileUpload.dto"
import UserAvatarsService from "../userAvatars/userAvatars.service"
@Controller("users")
export class UsersController {
constructor(private readonly userAvatarsService: UserAvatarsService) {}
@Post("avatar")
@UseGuards(JwtAuthenticationGuard)
@UseInterceptors(
LocalFilesInterceptor({
fieldName: "file",
path: "/avatars",
fileFilter: (request, file, callback) => {
if (!file.mimetype.includes("image")) {
return callback(new BadRequestException("Provide a valid image"), false)
}
callback(null, true)
},
limits: {
fileSize: Math.pow(1024, 2), // 1MB
},
}),
)
@ApiConsumes("multipart/form-data")
@ApiBody({
description: "A new avatar for the user",
type: FileUploadDto,
})
async addAvatar(@Req() request: RequestWithUser, @UploadedFile() file: Express.Multer.File) {
return this.userAvatarsService.addAvatar(request.user.id, {
path: file.path,
filename: file.originalname,
mimetype: file.mimetype,
})
}
}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.