Ask Your Question
2

How can I inspect the data from a third-party API in between the controller and the request using NestJS?

asked 2022-04-12 11:00:00 +0000

pufferfish gravatar image

edit retag flag offensive close merge delete

1 Answer

Sort by ยป oldest newest most voted
0

answered 2021-04-25 23:00:00 +0000

woof gravatar image

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:

  • Create a middleware class that implements the NestJS 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();
  }
}
  • Register the middleware in the 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('*');
  }
}
  • The middleware logs the API request URL, request body, and query string parameters. It also overrides the response body to log the response from the third-party API.

You can customize the middleware class to log the specific data that you need to inspect from the third-party API.

edit flag offensive delete link more

Your Answer

Please start posting anonymously - your entry will be published after you log in or create a new account. This space is reserved only for answers. If you would like to engage in a discussion, please instead post a comment under the question or an answer that you would like to discuss

Add Answer


Question Tools

Stats

Asked: 2022-04-12 11:00:00 +0000

Seen: 13 times

Last updated: Apr 25 '21