I am using NestJs. I am using intercepter in my controller for PUT request.
I want to change the request body before the PUT request and I want to change response body that returns by PUT request. How to achieve that?
Using in PUT
@UseInterceptors(UpdateFlowInterceptor)
@Put('flows')
public updateFlow(@Body() flow: Flow): Observable<Flow> {
return this.apiFactory.getApiService().updateFlow(flow).pipe(catchError(error =>
of(new HttpException(error.message, 404))));
}
Interceptor
@Injectable()
export class UpdateFlowInterceptor implements NestInterceptor {
public intercept(_context: ExecutionContext, next: CallHandler): Observable<FlowUI> {
// how to change request also
return next.handle().pipe(
map(flow => {
flow.name = 'changeing response body';
return flow;
}),
);
}
}
I was able to do it by getting request
from ExecutionContext
following is the code.
@Injectable()
export class UpdateFlowInterceptor implements NestInterceptor {
public intercept(
_context: ExecutionContext,
next: CallHandler
): Observable<FlowUI> {
// changing request
let request = _context.switchToHttp().getRequest();
if (request.body.name) {
request.body.name = 'modify request';
}
return next.handle().pipe(
map((flow) => {
flow.name = 'changeing response body';
return flow;
})
);
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With