尝试验证typeorm实体的循环依赖

问题描述 投票:0回答:1

拥有这样的实体:

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

和自定义验证类

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)

因为对于我的验证逻辑,我需要运行一个查询,所以至少注入服务或存储库,我该怎么做呢?

nestjs typeorm class-validator
1个回答
0
投票

我在验证检查期间使用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

© www.soinside.com 2019 - 2024. All rights reserved.