Learn how to trigger an HTTP exception after a failed command in a saga with NestJS CQRS

Currently utilizing the NestJS CQRS pattern to handle interactions between User and UserProfile entities within my system. The setup consists of an API Gateway NestJS server along with dedicated NestJS servers for each microservice (User, UserProfile, etc.).

The basic communication is established through User and UserProfile modules on the API Gateway, complete with their respective sagas, events, and commands:

  • Creation of a user triggers creation of a corresponding user profile
  • If creation of the user profile fails, the previously created user is deleted

Here's how it works in detail:

Within the User module, executing the CreateUser command results in the UserCreated event being captured by the User saga. This then leads to triggering the CreateUserProfile command (belonging to the UserProfile module).

In case of failure, a UserProfileFailedToCreate event is generated, intercepted by the UserProfile saga, subsequently initiating the DeleteUser command (from the User module).

All operations are functioning correctly.

When the CreateUser command encounters an error, I use

resolve(Promise.reject(new HttpException(error, error.status))
to inform the user about the issue during user creation.

However, the challenge arises when attempting to replicate this behavior for the CreateUserProfile command as the HTTP request promise has already been resolved from the previous command execution.

Hence, my question is: Is there a way to trigger command failure if any subsequent command in the saga fails? Although the HTTP request remains detached from the subsequent actions initiated by a saga, I'm curious whether anyone has explored leveraging events or alternative approaches to emulate this data flow?

The primary reason behind opting for CQRS framework is not just for streamlined data interaction across microservices but also to have the ability to roll back repository actions in case of command chain failures, which is currently operational. However, I require a mechanism to notify the end user when a chain experiences an issue and undergoes rollback operation.

UserController.ts

@Post('createUser')
async createUser(@Body() createUserDto: CreateUserDto): Promise<{user: IAuthUser, token: string}> {
  const { authUser } = await this.authService.createAuthUser(createUserDto);
  // Executed post resolve() in CreateUserCommand
  return {user: authUser, token: this.authService.createAccessTokenFromUser(authUser)};
}

UserService.ts

async createAuthUser(createUserDto: CreateUserDto): Promise<{authUser: IAuthUser}> {
  return await this.commandBus
    .execute(new CreateAuthUserCommand(createUserDto))
    .catch(error => { throw new HttpException(error, error.status); });
}

CreateUserCommand.ts

async execute(command: CreateAuthUserCommand, resolve: (value?) => void) {
    const { createUserDto } = command;
    const createAuthUserDto: CreateAuthUserDto = {
      email: createUserDto.email,
      password: createUserDto.password,
      phoneNumber: createUserDto.phoneNumber,
    };

    try {
      const user = this.publisher.mergeObjectContext(
        await this.client
          .send<IAuthUser>({ cmd: 'createAuthUser' }, createAuthUserDto)
          .toPromise()
          .then((dbUser: IAuthUser) => {
            const {password, passwordConfirm, ...publicUser} = Object.assign(dbUser, createUserDto);
            return new AuthUser(publicUser);
          }),
      );
      user.notifyCreated();
      user.commit();
      resolve(user); 
    } catch (error) {
      resolve(Promise.reject(error));
    }
  }

UserSagas.ts

authUserCreated = (event$: EventObservable<any>): Observable<ICommand> => {
    return event$
      .ofType(AuthUserCreatedEvent)
      .pipe(
        map(event => {
          const createUserProfileDto: CreateUserProfileDto = {
            avatarUrl: '',
            firstName: event.authUser.firstName,
            lastName: event.authUser.lastName,
            nationality: '',
            userId: event.authUser.id,
            username: event.authUser.username,
          };
          return new CreateUserProfileCommand(createUserProfileDto);
        }),
      );
  }

CreateUserProfileCommand.ts

async execute(command: CreateUserProfileCommand, resolve: (value?) => void) {
    const { createUserProfileDto } = command;

    try {
      const userProfile = this.publisher.mergeObjectContext(
        await this.client
          .send<IUserProfile>({ cmd: 'createUserProfile' }, createUserProfileDto)
          .toPromise()
          .then((dbUserProfile: IUserProfile) => new UserProfile(dbUserProfile)),
      );
      userProfile.notifyCreated();
      userProfile.commit();
      resolve(userProfile);
    } catch (error) {
      const userProfile = this.publisher.mergeObjectContext(new UserProfile({id: createUserProfileDto.userId} as IUserProfile));
      userProfile.notifyFailedToCreate();
      userProfile.commit();
      resolve(Promise.reject(new HttpException(error, 500)).catch(() => {}));
    }
  }

UserProfileSagas.ts

userProfileFailedToCreate = (event$: EventObservable<any>): Observable<ICommand> => {
    return event$
      .ofType(UserProfileFailedToCreateEvent)
      .pipe(
        map(event => {
          return new DeleteAuthUserCommand(event.userProfile);
        }),
      );
  }

DeleteUserCommand.ts

async execute(command: DeleteAuthUserCommand, resolve: (value?) => void) {
    const { deleteAuthUserDto } = command;

    try {
      const user = this.publisher.mergeObjectContext(
        await this.client
          .send<IAuthUser>({ cmd: 'deleteAuthUser' }, deleteAuthUserDto)
          .toPromise()
          .then(() => new AuthUser({} as IAuthUser)),
      );
      user.notifyDeleted();
      user.commit();
      resolve(user);
    } catch (error) {
      resolve(Promise.reject(new HttpException(error, error.status)).catch(() => {}));
    }
  }

Answer №1

From a Domain Driven Design perspective, creating the entities User and UserProfile represents a crucial business transaction - a collection of business rules/operations that need to be consistent - across various microservices according to this source.

In this situation, if the database returns data for User before the creation of UserProfile, it could lead to inconsistent data being displayed. While not necessarily incorrect, it is important to handle this situation properly on the client side.

There are three potential approaches to address this issue:

  1. Allow the Sagas to complete their execution, indicating the end of the business transaction with success or failure outcomes only after all commands have been executed (error details can provide information about successful/unsuccessful steps). It is recommended not to resolve in CreateAuthUserCommand.

  2. If there may be delays in creating the UserProfile (e.g., manual validation by a Moderator), consider resolving the User in CreateAuthUserCommand first and then having the client subscribe to UserProfile-related events. Although a mechanism is required, it separates the client from the ongoing transaction, allowing it to perform other tasks.

  3. Alternatively, split the business transaction into two parts where the client sends separate requests: one request creates/returns the authenticated User, while the other request returns the created UserProfile. Even though User and UserProfile belong to the same bounded context, residing in different microservices suggests otherwise (suggesting Authentication and UserProfiles as distinct bounded contexts). Best practice involves each microservice implementing its own encapsulated bounded context.

(Note: Responded to an older query with the hope of providing useful information to others)

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

How to retrieve JSON data in Angular.js

I'm having trouble accessing a json file in angular.js with the code below. I keep getting an error message and could really use some help! Here is my module : angular.module("demoApp", ['demoApp.factory','demoApp.controllers']); ...

Global jQuery variables are unexpectedly coming back as "undefined" despite being declared globally

I need to save a value from a JSON object in a global variable for future use in my code. Despite trying to declare the country variable as global, it seems like it doesn't actually work. $.getJSON(reverseGeoRequestURL, function(reverseGeoResult){ ...

What is the best way to implement a new search input for my datatable while also enabling the searchHighlight feature?

I'm attempting to implement a search bar for my datatables. I need to hide the default search engine that comes with datatables, so I added a script that I found in a forum. However, when I try to run it in my code, it doesn't work and displays a ...

Using React to create multiple modals and dynamically passing props

Each item in my list (ProjectActivityList) has an Edit button which, when clicked, should open a modal for editing that specific item. The modal requires an ID to identify the item being edited. var ProjectActivities = React.createClass({ onEditItem: ...

Using the spread operator in ES6 allows for arguments to be placed in a non-con

When working in nodeJS, my code looks like this: path = 'public/MIN-1234'; path = path.split('/'); return path.join( process.cwd(), ...path); I was expecting to get: c:\CODE\public/MIN-1234 but instead, I got: `‌publ ...

What is the best way to replicate the Ctrl+A action on an element using jQuery or JavaScript?

Is there a way to trigger the Ctrl+A key combination in a textarea element when a specific event occurs, without resorting to caret positioning or selecting all text separately? I'm looking for a method that simulates hitting Ctrl+A using a cross-brow ...

What is the best way to represent a state with two possible fields in React using TypeScript?

There is a specific state item that can have its own value or reference another item using an ID. interface Item { itemName: string; itemValue: { valLiteral: number } | { idNumber: string }; } const indItem1: Item = { itemName: "first sample&quo ...

Error: The function used in Object(...) is not defined properly in the useAutocomplete file at line 241

I am currently working on a ReactJS application that utilizes Material UI components without the use of Redux. Everything is functioning properly in my application, except when I attempt to integrate the Material UI autocomplete feature, it encounters iss ...

Exploring JSON without taking into account letter case

Looking to conduct a case-insensitive search in a JSON file? Here's the JSON data you can work with: { "Data" : [ {"Name": "Widget", "Price": "25.00", "Quantity": "5" }, {"Name": "Thing", "Price": "15.00", "Quantity": "5" }, {"Nam ...

Tips for improving modularity in my frontend JavaScript code?

I'm currently developing a unique Node.js / Express application that visually represents text notes as a network to offer users a clear summary of the connections between different notes. The project heavily relies on frontend functionalities, requir ...

Despite the presence of data within the array, the React array returns empty when examined using the inspect element tool

Currently, I'm working on creating an array of objects in React. These objects consist of a name and a corresponding color, which is used to represent the pointer on Google Maps. For instance, one object would look like this: {name: "Ben", colour: "gr ...

Node.js CallbackHandler: Simplifying event handling in JavaScript applications

I implemented the following function in a .js file to handle an asynchronous network connection: function requestWatsonDiscovery(queryString) { console.log('Query =', queryString); if (typeof queryString !== 'undefined') { ...

A guide on implementing multiple ternary operators in a Vue.js template

Is it possible for a template to return three different values instead of just two, based on the data? I am familiar with using two conditions, but is there a way to use more than two without getting a syntax error? <option {{ change === 1 ? &apos ...

Retrieve data from backend table only once within the bootstrap modal

How can I retrieve values from a table once a modal is displayed with a form? I am currently unable to access the values from the table behind the modal. Are there any specific rules to follow? What mistake am I making? I would like to extract the values ...

How to handle an unexpected keyword 'true' error when using the `useState` hook in React?

Trying to set the open prop of the MUIDrawer component to true on user click is causing an error stating "Unexpected keyword 'true'" import React, { useState } from "react"; import { withRouter } from "react-router-dom"; impo ...

Validating Two DateTime Pickers as a Group with Javascript in asp.net

How to Ensure Group Validation of Two DateTime Pickers Using JavaScript in ASP.NET ...

Webpack returns an undefined error when attempting to add a JavaScript library

I am a newcomer to webpack and I am attempting to incorporate skrollr.js into my webpack setup so that I can use it as needed. However, I am unsure of the correct approach for this. After some research, I have found that I can either use an alias or export ...

Is there a way to differentiate between a plain object and a class instance in Typescript?

Specifically, I am looking to differentiate between primitive types and plain objects versus class instances. let x = {y:5} // this is acceptable class X { y = 5; } let x = new X(); // this is not permissible ...

Am I making a mistake in my implementation of sending Socket.io messages to a designated room?

Upon a user joining, I alter their ID to a shortened random code. This change is made to utilize the id as a visible session ID on the front-end. I mention this to prevent confusion regarding non-standard socket IDs and their relation to potential issues. ...

Displaying a timer output in an HTML div every second using PHP

I created a custom PHP countdown timer that displays the remaining time in hours, minutes, and seconds (specifically 3 hours) - named countdown.php. The timer output is displayed within a <div> tag on another page called index.html. Now, I am lookin ...