Question:
Ignore requests by interceptors based on request content in TypeScript?

Problem

How can I return a status 200 and abort the controller call if a specific key on the request payload matches my requirements?


I'm using >Interceptors on my application, but I couldn't figure out how to return a status "200" without throwing an exception.


Example:


@Injectable()

export class MyInterceptor implements NestInterceptor {

  intercept(

    context: ExecutionContext,

    next: CallHandler<any>,

  ): Observable<any> | Promise<Observable<any>> {

    const { data } = context.switchToHttp().getRequest().body as Message;

    const payload: InputData = JSON.parse(data.toString());


    if (payload.order.payment.type === 'MY_SPECIFIC_VALUE') {

      // How to return a success and abort the controller call?

      throw new HttpException(

        {

          message:

            'payment type is not supported, this message will be ignored.',

        },

        200,

      );

    }


    return next.handle();

  }

}


Solution

You can do something like


@Injectable()

export class MyInterceptor implements NestInterceptor {

  intercept(

    context: ExecutionContext,

    next: CallHandler<any>,

  ): Observable<any> | Promise<Observable<any>> {

    const { data } = context.switchToHttp().getRequest().body as Message;

    const payload: InputData = JSON.parse(data.toString());


    if (payload.order.payment.type === 'MY_SPECIFIC_VALUE') {

      // How to return a success and abort the controller call?

      const response = context.switchToHttp().getResponse<Response>();

      // depending on the underlying HTTP engine (express or fastify or other) this might need to be modified

      response.statusCode = 200;

      return of({

        message: 'payment type is not supported, this message will be ignored.' 

      });

    }


    return next.handle();

  }

}


and the interceptor will return that early instead of calling to your controller. of is an Observable creation operator from the rxjs package.


Suggested blogs:

>How to Select checkboxes on an HTML treeview with JavaScript?

>How to use querySelectorAll()" with multiple conditions in JavaScript?

>How to fix mouseover event glitch in JavaScript?

>How to do light and dark mode in a website using HTML and JavaScript?

>How to manipulate manipulating Array object in JavaScript?

>How to merge an object into Array with the same key in JavaScript?

>Javascript Error Solved: Property 'id' does not exist on type 'T'

>Why highlighted table row using class not working in JavaScript?

>How to rename an object key based on the condition in JavaScript?

>How to sort an array based on another array in Javascript?

>Javascript: Modal not closing with a button


Nisha Patel

Nisha Patel

Submit
0 Answers