Files
MultiTenantSaaS/common/interceptors/response.interceptor.ts
2026-03-04 22:26:20 +05:45

73 lines
1.7 KiB
TypeScript
Raw Permalink Blame History

This file contains invisible Unicode characters
This file contains invisible Unicode characters that are indistinguishable to humans but may be processed differently by a computer. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
import {
Injectable,
NestInterceptor,
ExecutionContext,
CallHandler,
} from '@nestjs/common';
import { DataResponse, MessageResponse } from 'common/http';
import { Observable } from 'rxjs';
import { map } from 'rxjs/operators';
@Injectable()
export class ResponseInterceptor<T> implements NestInterceptor<T, any> {
intercept(_: ExecutionContext, next: CallHandler): Observable<any> {
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<T> implements NestInterceptor<T, any> {
intercept(context: ExecutionContext, next: CallHandler): Observable<any> {
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<T>
This is:
An RxJS stream of whatever the controller returns
Not the request
Not the response object
Just the return value
* */