73 lines
1.7 KiB
TypeScript
73 lines
1.7 KiB
TypeScript
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
|
||
* */
|