mikro-orm / nestjs-realworld-example-app

Example real world backend API built with NestJS + MikroORM
https://realworld.io/
MIT License
280 stars 72 forks source link

How do I use an EntityManager or EntityRepository outside of a module #110

Closed 0x0bit closed 6 months ago

0x0bit commented 6 months ago

My project directory is as follows

├── src
│   ├── app.controller.ts
│   ├── app.module.ts
│   ├── common
│   │   ├── pipes
│   │   │   └── validation.pipe.ts
│   │   └── validators
│   │       ├── Is-valid-city.ts
│   │       └── Is-valid-provincial.ts
│   ├── config
│   │   ├── configuration.ts
│   │   ├── db-mysql.module.ts
│   │   └── env
│   │       └──default.yaml
│   ├── main.ts
│   ├── migrations
│   └── modules
│       └── districts
│          ├── districts.controller.ts
│          ├── districts.module.ts
│          ├── districts.service.ts
│          ├── dto
│          └── entities
├── tsconfig.build.json
└── tsconfig.json

For special reasons, I need a custom validator, and to query the database in the validator, I put the custom validators under /src/common/validators, The code of is-valid-provincial.ts Is as follows:

@ValidatorConstraint({ async: true })
export class IsValidProvincialConstraint
  implements ValidatorConstraintInterface
{
  constructor(
    @InjectRepository(DistrictsEntity)
    private readonly dr: EntityRepository<DistrictsEntity>,
  ) {}
  async validate(id: string) {
    const provincial = await this.dr.findOne({ id, level: 2 });
    return Boolean(provincial);
  }
}

export function IsValidProvincial(validationOptions?: ValidationOptions) {
  return function (object: any, propertyName: string) {
    registerDecorator({
      target: object.constructor,
      propertyName: propertyName,
      options: validationOptions,
      constraints: [],
      validator: IsValidProvincialConstraint,
    });
  };
}

But every time I got an error, I couldn't find the findOne method for Entity, even though I used service image

What am I supposed to do here? I hope you can help me. Thank you very much

B4nan commented 6 months ago

This is probably relevant: https://stackoverflow.com/questions/60062318/how-to-inject-service-to-validator-constraint-interface-in-nestjs-using-class-va

Your problem is about how you use nest, it has nothing to do with the ORM. You would get a better answer from nest community.