import { Injectable, NestInterceptor, ExecutionContext, CallHandler, } from '@nestjs/common'; import { DataResponse, MessageResponse } from 'common/http'; import { Observable } from 'rxjs'; import { catchError, map } from 'rxjs/operators'; @Injectable() export class ResponseInterceptor implements NestInterceptor { intercept(_: ExecutionContext, next: CallHandler): Observable { return next.handle().pipe( map((data) => { if (data instanceof MessageResponse) return data; else if (data instanceof DataResponse) return data; else if (typeof data === 'string') return new MessageResponse(data); return new DataResponse(data); }), ); } } /* NOTE: How to access request * @Injectable() export class ResponseInterceptor implements NestInterceptor { intercept(context: ExecutionContext, next: CallHandler): Observable { const req = context.switchToHttp().getRequest(); req.userId = 'ram'; return next.handle(); // return next.handle().pipe( // map((data) => { // if (data instanceof MessageResponse) return data; // else if (data instanceof DataResponse) return data; // else if (typeof data === 'string') return new MessageResponse(data); // return new DataResponse(data); // }), // ); } } REQUEST ↓ Guards ↓ Interceptors (before) ↓ Pipes ↓ Controller method ↓ Interceptors (after) ← YOU ARE HERE ↓ Response 3️⃣ What is next.handle() really? next.handle(): Observable This is: An RxJS stream of whatever the controller returns Not the request Not the response object Just the return value * */