【问题标题】:Custom Route Decorators for NestJSNestJS 的自定义路由装饰器
【发布时间】:2020-11-21 07:47:37
【问题描述】:

我已经为我的路线创建了一些custom parameter decorators,但我没有找到任何有用的文档来说明如何为路线本身创建装饰器。有一些描述如何将现有的方法装饰器捆绑在一起,这对我没有帮助。

我想要实现的是一些简单的范围验证。范围已在请求上下文中设置。我目前拥有的,仅基于TypeScript decorators,但实际上无处可去:

controller.ts

@RequiredScope(AuthScope.OWNER)
@Get('/some-route')
async get() {
    ...
}

required-scopes.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)
        }
    }
}

这里的问题是我的请求上下文甚至不可用,因为我设置上下文的中间件还没有启动。请求立即失败。

有人能指出我正确的方向吗?

【问题讨论】:

  • 你有没有试过用守卫代替装饰器? docs.nestjs.com/guards
  • 非常感谢您的建议。结果非常好。此外,它更适合这个用例。

标签: javascript typescript nestjs typescript-decorator


【解决方案1】:

正如Khaled Mohamed(谢谢!)所提议的那样,用警卫解决这个问题非常简单,而且是一种更好的方法。


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

export const Scopes = (...scopes: string[]) => SetMetadata('scopes', scopes)

设置检查提供的元scopes 并检查是否满足 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() {
    ...
}

【讨论】:

    猜你喜欢
    • 2018-06-05
    • 2020-06-30
    • 2012-06-19
    • 2021-09-30
    • 2021-02-06
    • 2021-04-11
    • 2013-02-06
    • 2020-07-02
    • 2023-03-21
    相关资源
    最近更新 更多