file two.js: undefined 2file one.js: 12(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.
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.
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.
import{HttpException,HttpStatus,Injectable}from'@nestjs/common';import{InjectRepository}from'@nestjs/typeorm';import{Repository}from'typeorm';importUserfrom'./user.entity';importLocalFilesServicefrom'../localFiles/localFiles.service';@Injectable()exportclassUsersService{constructor(@InjectRepository(User)privateusersRepository:Repository<User>,privatelocalFilesService:LocalFilesService,){}asyncgetById(id:number){constuser=awaitthis.usersRepository.findOne({id});if(user){returnuser;}thrownewHttpException('User with this id does not exist',HttpStatus.NOT_FOUND,);}asyncaddAvatar(userId:number,fileData:LocalFileDto){constavatar=awaitthis.localFilesService.saveLocalFileData(fileData);awaitthis.usersRepository.update(userId,{avatarId:avatar.id,});}// ...}
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.
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.
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.
import{BadRequestException,Controller,Post,Req,UploadedFile,UseGuards,UseInterceptors,}from'@nestjs/common';importJwtAuthenticationGuardfrom'../authentication/jwt-authentication.guard';importRequestWithUserfrom'../authentication/requestWithUser.interface';import{Express}from'express';importLocalFilesInterceptorfrom'../localFiles/localFiles.interceptor';import{ApiBody,ApiConsumes}from'@nestjs/swagger';importFileUploadDtofrom'./dto/fileUpload.dto';importUserAvatarsServicefrom'../userAvatars/userAvatars.service';@Controller('users')exportclassUsersController{constructor(privatereadonlyuserAvatarsService:UserAvatarsService){}@Post('avatar')@UseGuards(JwtAuthenticationGuard)@UseInterceptors(LocalFilesInterceptor({fieldName:'file',path:'/avatars',fileFilter:(request,file,callback)=>{if(!file.mimetype.includes('image')){returncallback(newBadRequestException('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,})asyncaddAvatar(@Req()request:RequestWithUser,@UploadedFile()file:Express.Multer.File,){returnthis.userAvatarsService.addAvatar(request.user.id,{path:file.path,filename:file.originalname,mimetype:file.mimetype,});}}