Ways to decline requests using interceptors depending on the content of the request?

Is there a way to achieve a status of 200 and stop the controller call if a certain key in the request payload meets my criteria?

I've implemented Interceptors in my application, but I'm struggling to send a status of "200" without causing an exception.

For instance:

@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 can I return a success response and halt the controller call?
      throw new HttpException(
        {
          message:
            'payment type is not supported, this message will be ignored.',
        },
        200,
      );
    }

    return next.handle();
  }
}

Answer №1

If you want to implement this logic, you can consider the following approach:

@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') {
      // Return a success response and stop the controller call
      const response = context.switchToHttp().getResponse<Response>();
      response.statusCode = 200;
      return of({
        message: 'Payment type is not supported, this message will be ignored.' 
      });
    }

    return next.handle();
  }
}

The interceptor will handle the logic and return a response early without calling the controller. The of operator is used to create Observables from the rxjs package.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Unexpected issue occurred in Angular 16 when utilizing less compiler. Error message displayed: "URL token should be closed with a ')'."

I'm having trouble locating the missing parenthesis. It seems like the issue may not be in this file. Any suggestions on how to troubleshoot this? I've already disabled optimization "optimization": false ./src/main.ts - Error: Mod ...

Ensuring Uniform Data Types Across Objects (Using Typescript)

After much trial and error, I have finally reached this point where everything seems to be working perfectly. function test<types extends Record<string,any>>(dict: dictionary<types>){} type dictionary<types extends Record<string, a ...

How can I combine multiple styles using Material-UI themes in TypeScript?

There are two different styles implementations in my code. The first one is located in global.ts: const globalStyles = (theme: Theme) => { return { g: { marginRight: theme.spacing(40), }, } } export const mergedStyle = (params: any) ...

Conditional types allow the function parameter type to be determined based on the type of another parameter

Here: function customFunction<T extends boolean> (param1: T, param2: T extends true ? number[] : number) { if (param1) { let result: number[] = param2; // Type 'number' is not assignable to type 'number[]'.(2322) } } ...

Issue with the loading of Firebase in Chrome extension's background script is inconsistent

I am currently working on developing a Chrome extension that utilizes Google Firebase for authentication. In my project, I am employing webpack for building purposes, with Firebase being utilized in the background script. However, during the initial initi ...

Incorporating TypeScript basics into the if statement post compiling

As I delve into the Angular2 Quickstart, I stumbled upon a peculiar issue within app.component.js after compiling app.component.ts using tsc (version 1.8.2): if (d = decorators[i]) I am unable to pinpoint where I may have gone wrong in configuring the qu ...

Transform an array of Boolean values into a string array containing only the values that are true

Suppose we have an object like the following: likedFoods:{ pizza:true, pasta:false, steak:true, salad:false } We want to filter out the false values and convert it into a string array as shown below: compiledLikedFoods = ["pizza", "steak"] Is t ...

What is the best way to retrieve an object within a class?

Exploring a Class Structure: export class LayerEditor { public layerManager: LayerManager; public commandManager: CommandManager; public tools: EditorTools; constructor() { this.commandManager = new CommandManager(); this.lay ...

Authentication of users using NextJS Dashboard App API

I am currently following this tutorial, but instead of fetching data via a PostgreSQL request, I want to utilize an API. When I call an async function with await, it initially returns undefined and then the user object after receiving a response from the ...

Ways to verify the functionality of a function utilizing a Subscription that yields no return value

I'm working with a TypeScript ModelService that has an edit function: edit(model: Model): Observable<Model> { const body = JSON.stringify(model); return this.http.put(`/models/edit/${model.id}`, body)); } Additionally, there is a TypeScrip ...

Issues encountered when trying to upload images to Firestore Storage

I am attempting to upload an image and store its URL in a Firestore document. To achieve this, I have the following code snippet: This function uses the device camera to capture the photo. selectImage(): Promise<any> { return new Promise(resolv ...

Issues with tracking changes in Vue.js when using reactive variables

After triggering a click event, I am attempting to choose a message from a json file. However, I am encountering an issue where the first click does not seem to select anything. Upon the second click, the selected messages are duplicated, and this pattern ...

How can you debug a Node.js CLI tool using WebStorm?

Struggling to develop a CLI tool using TypeScript within WebStorm as my IDE. No matter what I try, debugging just won't work for me. My journey in Node.js CLI programming started with this tutorial. Successfully transpiling the TS source with npx tsc, ...

Manage interfaces and structures

I am looking to implement user roles in my application. Here is a snippet of the code I would like to use: export interface User{ name: string roles: Roles[] } interface Roles{ ADMIN: new Permissions(1,1,1,1,1), MOD: new Permissions(1,0,1,1,0,0), [. ...

Using Angular's ngFor directive to iterate over a collection based on a true

I am currently attempting to resolve the following condition: if the condition is true, display a button, otherwise hide the button. OfferMatching() { this.getmatchoffer.filter(obj => { debugger for (let i = 0; i < this.applicationJobList.length; i+ ...

Ways to resolve the issue of the 'setConfirmDelete' property not being found on type 'JSX.IntrinsicElements' in React.js

index.tsx const setConfirmDelete = (state, close) => { return ( <Modal show={state} onHide={close}> <Modal.Header> <Modal.Title>Title</Modal.Title> </Modal.Header> <Modal.Body> 'T ...

Cease the animated loading icon once the template has finished loading in sync with the async pipe

.ts initialize() { const loadingScreen = await this.loadingService.displayLoader();//loading screen this.products$ = this.bikeShopService.retrieveData();//Observable operation } .html <ion-col size="6" *ngFor="let product of (products$ ...

Issue: Unable to locate the name 'ContactField' in Ionic 2

While attempting to use Ionic2 to save a contact, an error occurs when running the app through the command line. The cordova-plugin-contacts has been properly installed. Below is the code snippet: import { Component } from '@angular/core'; impo ...

Retrieving an array of objects from an API and attempting to store it using useState, but only receiving an empty

I have been working on fetching data from an API, storing it in Redux store initially, and then attempting to retrieve it using useSlector to finally save it in local state. Despite getting the data when I console.log it, I am unable to successfully store ...

There is an issue with the typings for React.createElement that is causing errors

Is it possible to implement React.createElement with TypeScript successfully? import React from "react"; type Props = { label: string; }; const Three: React.FC<Props> = (props: Props) => { return <div>{props.label}</div&g ...