DEV Community

Cover image for Using NestInterceptor to capture requests and responses
Visakh Vijayan
Visakh Vijayan

Posted on • Edited on

7 2

Using NestInterceptor to capture requests and responses

We needed a provision to capture API requests and responses. This was so that our mobile team could get a summary of what the app was sending and receiving. Once captured we wrote them in a file in the last-in-first-seen order.

We eventually started off by implementing the Nest Middleware but then we realized a middleware can only receive requests. So we switched to Interceptors.

An interceptor has access to both requests and responses.

Here is the code.

class LoggerInterceptor implements NestInterceptor
{
    intercept(context: ExecutionContext, next: CallHandler): Observable<any>
    {
        let logFile = process.env.LOGGER_APP + ".log";
        let logPath = process.cwd() + "<path>" + logFile;

        let { url, method, headers, body } = context.switchToHttp().getRequest();

        if (url != "/logs/dev.log")
        {
            let logMessage = "\n\n=======================================\n\nTIME: " + Date().toString() + "\nMETHOD: " + JSON.stringify(method) + "\nURL: " + JSON.stringify(url) + "\nHEADERS: " + JSON.stringify(headers) + "\nBODY: " + JSON.stringify(body) + "\nRESPONSE: ";

            return next.handle().pipe(tap((data) => 
            {
                let responseBody = JSON.stringify(data);

                logMessage += responseBody;

                // Reading old data.
                logMessage += fs.readFileSync(logPath);

                fs.writeFile(logPath, logMessage, function (err, file) { });
            }));
        }
    }
}
Enter fullscreen mode Exit fullscreen mode

A couple of points worth mentioning -

  1. is the path to where your log files should be stored. We wanted the app team to have access to the logs so we kept them in a public folder.
  2. We put up a check (!= "/logs/dev.log") to prevent logging access to the log file into the log file :D Lol!

Happy Programming!!!

Heroku

This site is built on Heroku

Join the ranks of developers at Salesforce, Airbase, DEV, and more who deploy their mission critical applications on Heroku. Sign up today and launch your first app!

Get Started

Top comments (1)

Collapse
 
vbao profile image
csvobao

Thanks a lot, this work for me!

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs