簡體   English   中英

NestJS 的自定義路由裝飾器

[英]Custom Route Decorators for NestJS

我已經為我的路線創建了一些自定義參數裝飾器,但我沒有找到任何有用的文檔來說明如何為路線本身創建裝飾器。 有一些描述如何將現有的方法裝飾器捆綁在一起,這對我沒有幫助。

我想要實現的是一些簡單的 scope 驗證。 范圍已在請求上下文中設置。 我目前擁有的,僅基於TypeScript 裝飾器,但實際上無處可去:

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提出的(謝謝,)。 用警衛解決這個問題非常簡單,也是一種更好的方法。


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() {
    ...
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM