gpt4 book ai didi

javascript - NestJS 的自定义路由装饰器

转载 作者:行者123 更新时间:2023-12-05 00:37:27 25 4
gpt4 key购买 nike

我创建了一些 custom parameter decorators对于我的路线,但我没有找到任何有关如何为路线本身创建装饰器的有用文档。有一些描述如何将现有的方法装饰器捆绑在一起,这对我没有帮助。
我想要实现的是一些简单的范围验证。范围已在请求上下文中设置。我目前拥有的,仅基于TypeScript decorators ,但实际上无处可去:
Controller .ts

@RequiredScope(AuthScope.OWNER)
@Get('/some-route')
async get() {
...
}
所需范围.ts
export function RequiredScope(...scopes: string[]) {
return (target: any, propertyKey: string, descriptor: PropertyDescriptor) => {
console.log(`Validation of scopes '${scopes.join(',')}' for input '${RequestContext.getScopes().join(',')}'`)
if (!scopes.map(s => RequestContext.hasOneOfTheScopes(s)).find(valid => !valid)) {
throw new HttpException(`Missing at least one scope of '${scopes.join(',')}'`, HttpStatus.FORBIDDEN)
}
}
}
这里的问题是我的请求上下文甚至不可用,因为我的设置上下文的中间件还没有启动。请求立即失败。
有人可以指出我正确的方向吗?

最佳答案

Khaled Mohamed 提出(谢谢!),用 guard 解决这个问题非常简单,也是一种更好的方法。

中创建具有所需范围作为参数的装饰器scopes.decorator.ts :

export const Scopes = (...scopes: string[]) => SetMetadata('scopes', scopes)
设置一个检查提供的元 scopes 的 guard 并检查 中的要求是否得到满足scopes.guard.ts :
@Injectable()
export class ScopesGuard implements CanActivate {

constructor(private reflector: Reflector) {}

canActivate(
context: ExecutionContext,
): boolean | Promise<boolean> | Observable<boolean> {
const scopes = this.reflector.get<string[]>('scopes', context.getHandler())
if (!scopes || scopes.length === 0) return true
if (!scopes.map(s => RequestContext.hasOneOfTheScopes(s)).find(valid => !valid)) {
throw new HttpException(`Missing at least one scope of '${scopes.join(',')}'`, HttpStatus.FORBIDDEN)
}
return true
}
}

中全局激活守卫app.module.ts :
@Module({
imports: [...],
controllers: [...],
providers: [
{
provide: APP_GUARD,
useClass: ScopesGuard,
}
],
})
中的路线上使用装饰器 Controller .ts :
@Scopes(AuthScope.OWNER)
@Get('/some-route')
async get() {
...
}

关于javascript - NestJS 的自定义路由装饰器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63192245/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com