【问题标题】:Access a repo in a guard in nestjs在nestjs中访问一个repo
【发布时间】:2022-07-28 15:27:10
【问题描述】:

在升级到 typeorm 0.3 之前,我可以在我的守卫中使用 getConnection().getRepository<User>(User) 来获取一个类型的 repo 并对其进行操作。 但是,不推荐使用 0.3(另请参阅https://newreleases.io/project/github/typeorm/typeorm/release/0.3.0),现在我无法再访问我的后卫中的数据库了。我尝试使用

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

在守卫的构造函数中,然后尝试使守卫成为我导出的模块中的提供者,但也没有用。

所以我想知道如何访问那里的存储库或连接。否则我可能需要将我的连接详细信息传递给 Guard 并创建一个看起来很棒的新连接。

【问题讨论】:

  • 嘿,你有什么解决方法吗?
  • 不幸的是还没有。如果你找到了,请告诉我!
  • 我发现它让我发布我的答案。

标签: nestjs typeorm


【解决方案1】:

你可以试试 mixin https://wanago.io/2021/12/13/api-nestjs-mixin-pattern/。 检查传递附加参数部分。

我已经用 DataSource 完成了,你也可以使用 Repository。

//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;

控制器代码

import ScopeGuard from "app/modules/guards/scope.guard";

@UseGuards(ScopeGuard(User))

【讨论】:

    猜你喜欢
    • 2020-12-21
    • 1970-01-01
    • 2020-10-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-05-02
    • 2011-06-07
    • 2022-11-10
    相关资源
    最近更新 更多