node.js - 如何在警卫(ResourceOwnerGuard)之前执行管道(ValidateObjectId)?
问题描述
我在玩 Nestjs 和猫鼬。
编码:
class BrevesController {
constructor(private readonly brevesService: BrevesService) { }
// Here is used BreveOwnerGuard(1)
@UseGuards(JwtAuthGuard, BreveOwnerGuard)
@Get(':breveId')
// Here is used ValidateObjectId(3)
async getById(@Param('breveId', ValidateObjectId) id: string) {
return await this.brevesService.getById(id)
}
}
class BreveOwnerGuard {
constructor(private readonly brevesService: BrevesService) { }
async canActivate(context: ExecutionContext) {
const req = context.switchToHttp().getRequest()
const {user, params} = req
const {breveId} = params
// This is executed before ValidateObjectId in getById
// route handler and unknown error is thrown but we
// have pipe for this.(2)
const breve = await this.brevesService.getById(breveId)
const breveCreatorId = breve.creatorId.toString()
const userId = user.id
return breveCreatorId === userId
}
}
因此,在请求 /breves/:breveId 带有无效对象 id 之后,BreveOwnerGuard 在 ValidateObjectId 之前执行并抛出未知错误。
这个流程有没有办法在 BreveOwnerGuard 之前验证 ObjectId ?
或者在这种情况下我应该怎么做?期望什么?
解决方案
守卫在每个中间件之后执行,但在任何拦截器或管道之前。
- 资料来源:Guard Docs(我强调)
ResourceOwnerGuard
除了将 更改为管道或更改ValidateObjectId
为 Guard之外,您无能为力。
推荐阅读
- ansible - 在导入任务中的不同主机上运行任务
- r - R中的唯一/不同,不保留任何非唯一行
- excel-formula - 如何在Excel中删除重复的行值
- typescript - Vue组件导入接口时如何避免TS2614错误
- amazon-web-services - 具有代理集成的 AWS HTTP API 网关 - 模型
- elasticsearch - 复杂的嵌套查询在哪里放置布尔匹配
- r - 如何在 R 的 Leaflet 弹出标签中包含图像?
- c# - 起订量:更改设置返回处理异步参数的通用方法
- r - R根据其他列值设置列值
- graphql - 你可以为 GraphQL 中的 String 之类的基本类型起别名吗?像`type Token = String`?