import { Injectable, NestInterceptor as INestInterceptor, ExecutionContext, CallHandler } from "@nestjs/common" import { Observable } from "rxjs" import { map } from "rxjs/operators" const ObservableToPromise = (observable:Observable):Promise => { return new Promise((res,rej)=>{ observable.subscribe({ next:val=>{ res(val) }, error:err=>{ rej(err) } }) }) } export interface NestInterceptorBeforeHanlder { (context:ExecutionContext):Promise } export interface NestInterceptorResponseHandler { (response:any):Promise } @Injectable() export class NestInterceptor implements INestInterceptor{ private beforeHandlerList:NestInterceptorBeforeHanlder[] = [] private responseHandler:NestInterceptorResponseHandler|null = null public async intercept(context:ExecutionContext,next:CallHandler):Promise> { if ( this.beforeHandlerList.length > 0 ) { for ( let handle of this.beforeHandlerList.values() ) { await handle(context) } } if ( this.responseHandler === null ) { return next.handle() } else { let observableValue = await ObservableToPromise(next.handle()) let response = await this.responseHandler(observableValue) return next.handle().pipe( map(val=>response) ) } } public addBeforeHandler(handler:NestInterceptorBeforeHanlder):this { this.beforeHandlerList.push(handler) return this } public setReponseHandler(handler:NestInterceptorResponseHandler):this { this.responseHandler = handler return this } }