You can intercept the request and response using NestJS middleware to inspect the data from a third-party API in between the controller and the request.
Here is an example of how you can implement this:
Middleware
interface and overrides the use()
method:import { Injectable, NestMiddleware } from '@nestjs/common';
import { Request, Response } from 'express';
@Injectable()
export class ApiLoggerMiddleware implements NestMiddleware {
use(req: Request, res: Response, next: () => void) {
console.log(`Requesting API: ${req.originalUrl}`);
console.log(`Request body: ${JSON.stringify(req.body)}`);
console.log(`Request query parameters: ${JSON.stringify(req.query)}`);
const originalSend = res.send;
res.send = function bodyWrapper(body) {
console.log(`API Response Body: ${JSON.stringify(body)}`);
originalSend.call(this, body);
};
next();
}
}
app.module.ts
file:import { Module, NestModule, MiddlewareConsumer } from '@nestjs/common';
import { ApiLoggerMiddleware } from './api.logger.middleware';
@Module({
imports: [/*your modules here*/],
controllers: [/*your controllers here*/],
})
export class AppModule implements NestModule {
configure(consumer: MiddlewareConsumer) {
consumer.apply(ApiLoggerMiddleware).forRoutes('*');
}
}
You can customize the middleware class to log the specific data that you need to inspect from the third-party API.
Asked: 2022-04-12 11:00:00 +0000
Seen: 13 times
Last updated: Apr 25 '21