循环依赖试图验证Typeorm实体

时间:2019-04-28 06:37:52

标签: nestjs typeorm class-validator

具有这样的实体:

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)

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

2 个答案:

答案 0 :(得分: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

答案 1 :(得分:0)

我花了一周的时间来解决这样的问题。因此,我解决了这个问题,只是更改了保存实体的存储库方法。 我使用了repository.save(实体),并且总是由于循环依赖而失败。

切换到 repository.createQueryBuilder() 。插入() .into(TABLE_NAME) .values(实体) 。执行(); 该错误已清除。我真的建议尝试更改存储库方法,因为因为save()方法等待完整的实体集,而createQueryBuilder()接受实体值并将其转换为字符串值,从而进行常规查询。 < / p>

我正在使用无服务器和Webpack。 Typeorm不适用于webpack。