循环依赖试图验证 typeorm 实体

Circular dependency trying to validate typeorm entity

拥有这样的实体:

import { UniqueOrganizationPrincipal } from './constraints/unique-organization-principal';
import { Role } from './role.entity';

@Entity()
export class UserOrganization {
  @ManyToOne(type => Role, role => role.userOrganizations, { nullable: false, eager: true })
  @UniqueOrganizationPrincipal()
  role: Role;

  ... other fields ...
}

和自定义验证 class

import { Role } from '../role.entity';
import { UserOrganizationService } from '../user-organization.service';

@ValidatorConstraint({ async: true })
@Injectable()
export class UniqueOrganizationPrincipalConstraint implements ValidatorConstraintInterface {
  constructor(
    @Inject('UserOrganizationService') private readonly userService: UserOrganizationService
  ) { }


 async validate(role: Role, args: ValidationArguments) {
   .....
 }

  defaultMessage() {
    return 'error here';
  }
}

export function UniqueOrganizationPrincipal(validationOptions?: ValidationOptions) {
  return (object: object, propertyName: string) => {
    registerDecorator({
      target: object.constructor,
      propertyName,
      options: validationOptions,
      constraints: [],
      validator: UniqueOrganizationPrincipalConstraint
    });
  };
}

以及注入实体存储库的服务

@Injectable()
export class UserOrganizationService {
  constructor(
    @InjectRepository(UserOrganization)
    private readonly userOrganizationRepository: Repository<UserOrganization>
  ) {}

我收到这个错误:

/project/node_modules/@nestjs/typeorm/dist/common/typeorm.utils.js:14
        throw new circular_dependency_exception_1.CircularDependencyException('@InjectRepository()');
              ^
Error: A circular dependency has been detected inside @InjectRepository(). Please, make sure that each side of a bidirectional relationships are decorated with "forwardRef()". Also, try to eliminate barrel files because they can lead to an unexpected behavior too.
    at Object.getRepositoryToken (/project/node_modules/@nestjs/typeorm/dist/common/typeorm.utils.js:14:15)
    at Object.exports.InjectRepository (/project/node_modules/@nestjs/typeorm/dist/common/typeorm.decorators.js:6:130)
    at Object.<anonymous> (/project/src/user/user-organization.service.ts:14:6)
    at Module._compile (internal/modules/cjs/loader.js:805:30)
    at Module.m._compile (/project/node_modules/ts-node/src/index.ts:439:23)
    at Module._extensions..js (internal/modules/cjs/loader.js:816:10)
    at Object.require.extensions.(anonymous function) [as .ts] (/project/node_modules/ts-node/src/index.ts:442:12)
    at Module.load (internal/modules/cjs/loader.js:672:32)
    at tryModuleLoad (internal/modules/cjs/loader.js:612:12)
    at Function.Module._load (internal/modules/cjs/loader.js:604:3)

因为我的验证逻辑需要 运行 查询,所以至少要注入服务或存储库,我应该如何获取它?

我在验证检查期间使用 ModuleRef 修复了它

@ValidatorConstraint({ async: true })
@Injectable()
export class UniqueOrganizationPrincipalConstraint implements ValidatorConstraintInterface {
  private userOrganizationService: UserOrganizationService;

  constructor(private readonly moduleRef: ModuleRef) { }

  async validate(role: Role, args: ValidationArguments) {
    if (!this.userOrganizationService) {
      this.userOrganizationService = this.moduleRef.get('UserOrganizationService');
    }
    ... other code...
  }
}

有关 ModuleRef 的文档可在此处找到

https://docs.nestjs.com/fundamentals/circular-dependency#module-reference

我花了一个星期试图解决这样的问题。所以我解决了这个问题,只是更改了保存实体的存储库方法。 我使用了repository.save(实体)并且总是因循环依赖而失败。

切换到之后 repository.createQueryBuilder() 。插入() .into(TABLE_NAME) .values(实体) 。执行(); 此错误已被清除。我真的建议尝试更改存储库方法,因为 save() 方法等待完整的实体集,而 createQueryBuilder() 获取实体值并将它们转换为字符串值,进行正常查询。

我使用的是无服务器和 webpack。 Typeorm 不适用于 webpack。