跳转至

处理循环依赖项

node.js 模块中的循环依赖项

当两个文件相互导入时,就会发生循环依赖。 让我们来看看这个简单的例子:

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:

1
2
3
4
5
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.

使用 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-import

The 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,
    // ...
  },
  // ...
};

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.

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

users.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,
    });
  }

  // ...
}

使用正向引用解决问题

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:

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

users.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.

类型实体之间的循环依赖性

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.

在我们的架构中避免循环依赖

不幸的是,在我们的模块中有循环依赖通常是值得改进的设计的标志。 在我们的案例中,我们违反了 SOLID 的单一责任原则。 我们的 LocalFilesService 和 UsersService 负责多个功能。

如果你想了解更多关于 SOLID 的知识,请查看应用 SOLID 原则到你的 TypeScript 代码

我们可以创建一个服务来封装那些可能导致循环依赖问题的功能。

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

我们现在可以直接在 UsersController 中使用上面的服务,或者为新服务创建一个全新的控制器。

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,
    });
  }
}

总结

在本文中,我们研究了 Node.js 和 NestJS 上下文中的循环依赖关系问题。 我们已经了解了 Node.js 如何处理循环依赖关系,以及它如何导致难以预测的问题。 我们还使用前向引用处理了跨 NestJS 的循环依赖关系。 因为这只是一种解决方案,循环依赖项可能意味着缺乏设计,所以我们重写了代码来消除它。 这通常是最好的方法,我们应该避免在体系结构中引入循环依赖。