sungkwangsong
sungkwangsong

Reputation: 5655

How to use the AWS X-Ray with Nest.js?

AWS X-Ray is support Express and Restify middleware but not support Nest.js. Nest.js can't open segment and close segment to AWSXRay because it routes with typescript decoration. How to use the AWS X-Ray with the Nest.js

Upvotes: 5

Views: 2187

Answers (1)

Jay McDoniel
Jay McDoniel

Reputation: 70211

Hmm, this is one of those situations that could be very interesting and difficult to work with. You can of course set up the openSegement call in the standard Nest middleware (looks just like Express middleware), but the closeSegment is a bit more difficult. I think (and I'm taking a long shot here as I have no real way to test this) you can create an interceptor and inject the HttpAdapter into it, check in incoming route before the request is made and see if it is a route you want to cover with X-Ray, if so mark a boolean and in the observable response (next.handle()) you can get the HttpAdapter instance and call the closeSegment function. In other words (and this will be really rough code):

import { Injectable, NestInterceptor, ExecutionContext, CallHandler } from '@nestjs/common';
import { HttpAdapterHost } from '@nesjts/core';
import { Observable } from 'rxjs';
import { tap } from 'rxjs/operators';
import * as xRay from 'aws-xray-sdk-express';

@Injectable
export class XRayInterceptor implements NestInterceptor {
  constructor(private readonly httpAdapter: HttpAdapterHost) {}

  intercept(context: ExecutionContext, next: CallHandler): Observable<any> {
    let coverRoute = false;
    const req = context.switchToHttp().getRequest();
    if (req.path === 'yourPath') {
      coverRoute = true;
    }
    return next.handle()
      .pipe(
        tap(() => (coverRoute && this.httpAdapter.use(xRay.xrayExpress.closeSegment()))
      );
}

You might also probably be able to set up the openSegment in the interceptor as well, but again, all of this is untested and may not work as expected. I'm jsut trying to think of a way to maybe make this possible. Without access to error handling middleware your options would be to look at interceptors and filters, and it seems the closeSegement is to be an error handler like filters would be, so I'm not sure how you would catch errors otherwise. Maybe a filter is the best route, you may just have to play with ideas from here. Hopefully someone can give a bit more insight.

Upvotes: 3

Related Questions