Search code examples
nestjstypeorm

Access a repo in a guard in nestjs


Before upgrading to typeorm 0.3 I could use getConnection().getRepository<User>(User) in my guard to get a repo for a type and operate on it. With 0.3 however that is deprecated (see also https://newreleases.io/project/github/typeorm/typeorm/release/0.3.0) and now I cannot get access to the db in my guard anymore. I tried to use

 @InjectRepository(User)
 private userRepo: Repository<User>,

in the guard's constructor and then tried to make the guard a provider from a module that I exported but also that didnt work.

So I wonder how to get access to a repo or connection there. Otherwise I would probably need to pass my connection details to the Guard and create a new connecion ther which seems aweful.


Solution

  • You can try with mixin https://wanago.io/2021/12/13/api-nestjs-mixin-pattern/. Check the section Passing additional arguments.

    I have done it with DataSource you can use Repository as well.

    //scope.guard.ts
    import { CanActivate, ExecutionContext, NotFoundException, Inject, Type, mixin } from "@nestjs/common";
    import { DataSource, getRepository, ObjectType } from "typeorm";
    import { Request } from "express";
    
    const ScopeGuard = (entityClass): Type<CanActivate> => {
    class ScopeGuardMixin {
    constructor(@Inject(DataSource) private readonly dataSource: DataSource) {}
    
    async canActivate(context: ExecutionContext): Promise<boolean> {
      console.log("here 1");
      console.log(entityClass);
      console.log("here 2");
      const request = context.switchToHttp().getRequest<Request>();
      console.log(await this.dataSource.getRepository(entityClass).findOneBy({ id: Number(request.params.id) }));
      return true;
    }
    }
    return mixin(ScopeGuardMixin);
    };
    export default ScopeGuard;
    

    Controller code

    import ScopeGuard from "app/modules/guards/scope.guard";
    
    @UseGuards(ScopeGuard(User))