NestJS how get access in pipe to repository in abscract controller

Viewed 215

I have BaseController ( Abstract ) that contains pipe CanGetPipe

export abstract class CanGetPipe implements PipeTransform {
  protected abstract readonly repository: Repository<IEntry>;
...

and mixin for it

export const makeCanGetPipe = (repoName: any) =>
  mixin(
    class extends CanGetPipe {
      protected readonly repository = getConnection().getRepository<IEntity>(repoName);
    },
  );

Get method of BaseControlle looks like:

  @Get('/:id')
  @UsePipes(makeCanGetPipe(REPOSITORY_NAME_FROM_CHILD_CONTROLLER))
  getOne(@ValidateData() validate: ValidateParam, @Param('id') id: number) {
    return this.Service.get(id, validate);
  }

How i can set REPOSITORY_NAME_FROM_CHILD_CONTROLLER in child Controller than inherited from BaseController?
Or, how i can have access to repository (service, dependency) of child Controller in pipe that assigned to BaseController?

1 Answers

I think you can use combination of:

  1. @SetMetadata('repoName', YOUR_VALUE) on your child class
  2. Instead of Pipe - use Guard with const repoName = this.reflector.get<string>('repoName', context.getClass());

That should do the trick and you'll be able to get custom repo for your BaseGuard :)

Related