Selecting logic depending on the request body in NestJS

Currently, my controller looks like the following:

@Controller("workflow")
export class TaskWorkflowController {
  public constructor(
    private readonly jobApplicationActivityWorkflow: JobApplicationActivityService
  ) {}

  @Post("/:job-application-activity")
  public startWorkflow(
    @Body() body: StartJobApplication | StartJobActivity,
    @Param("job-application-activity") jobApplicationActivity: string
  ): void {
    switch (jobApplicationActivity) {
      case "job-application":
        return this.jobApplication.execute(body);
      case "job-activity":
        return this.jobActivity.execute(body);
      default:
        throw new Error("Invalid workflow");
    }
  }

The scenario I am facing is triggering different logic based on the job-application-activity parameter. The issue arises from having a body of type

StartJobApplication | StartJobActivity
, while my services are of type StartJobApplication and StartJobActivity.

How can I address this complication?

Answer №1

One challenge you may encounter is the inability to perform validation because Typescript does not accurately represent the union type. However, if this limitation is not a deal-breaker for you, consider implementing a type guard instead of a switch statement. You can achieve this by:

@Controller("workflow")
export class TaskWorkflowController {
  public constructor(
    private readonly jobApplicationActivityWorkflow: JobApplicationActivityService
  ) {}

  @Post("/:job-application-activity")
  public startWorkflow(
    @Body() body: StartJobApplication | StartJobActivity,
    @Param("job-application-activity") jobApplicationActivity: string
  ): void {
    if (jobApplicationActivity.propertyOnlyOnStartJobApplication) {
        return this.jobApplication.execute(body);
    } else if(jobApplicationActivity.propertyOnlyOnStartJobActivity)
        return this.jobActivity.execute(body);
    } else {
        throw new Error("Invalid workflow");
    }
  }
}

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

Is there a way in Express.JS to specify response status using a name instead of a number?

It is common knowledge that 200 means OK and 404 signifies not found. However, when dealing with HTTP error codes like permanent vs temporary redirect, or payment required, it may be more beneficial to approach it in the following manner: response.status( ...

Building an efficient MongoDB, Express, and React application involves properly defining the variable name that will be stored in the database

As a beginner in coding, I often struggle with the basics. Currently, I am working on creating a URL-Shortener using Express and MongoDB, along with React for the frontend. After setting up an input field and a submit button, I can successfully send the ...

Body Parser causing unexpected output

Currently encountering an issue when attempting to log the body of a POST request in my console. Despite seeing the payload in my Chrome console with the correct data, I am receiving the following error: express_1 | TypeError: Cannot read property ' ...

I can't find my unit test in the Test Explorer

I'm currently working on configuring a unit test in Typescript using tsUnit. To ensure that everything is set up correctly, I've created a simple test. However, whenever I try to run all tests in Test Explorer, no results are displayed! It appear ...

`Looking for information on configuring express.js settings?`

I feel a little embarrassed to have to ask, but does anyone know where I can get details on the settings available in express.js? The documentation mentions using app.set(name, setting) to define a setting for a specific name, but I'm having trouble l ...

A node is receiving a JSON object through an axios POST request

I am working on a project where I have two unique URLs. The first URL receives a form action from an HTML page along with data and then makes a post request to the second URL. The second URL, in turn, receives a JSON and uses Express to make a GET request ...

I am attempting to create a multi-line tooltip for the mat-icon without displaying " " in the tooltip

I attempted to create a multiline tooltip using the example below. However, the \n is showing up in the tooltip. I am looking to add a line break like we would with an HTML tooltip. Check out the code here. ...

Error: Cannot access Angular 5 Title service at this time

When attempting to change the page title using BrowserModule, I encountered an issue. I added the BrowserModule and Title in the application module as shown here: https://angular.io/guide/set-document-title However, in a child module where I tried to add ...

What is the best way to send multiple parameters to @Directives or @Components in Angular using TypeScript?

I am facing some confusion after creating @Directive as SelectableDirective. Specifically, I am unclear on how to pass multiple values to the custom directive. Despite my extensive search efforts, I have been unable to find a suitable solution using Angula ...

using the ng2-accordion component in your Angular 2 project

I am having trouble with the angular-2 accordion I implemented. It is not functioning properly and throwing a 404 error. The issue seems to be related to a third-party plugin called "ng2-accordion." I have double-checked the path of the package and it is ...

The transition between React server-side and client-side rendering is not perfectly smooth

Initially, the server rendered the page, but then on the client/browser side, the Javascript script re-renders the entire page! This approach does not provide a good user experience. One issue I noticed is that the data-reactid attribute on my root elem ...

Utilizing AJAX for passport verification and validation

My objective is to implement user authentication through ajax using passport. The usual method of utilizing passport involves initiating the authorization process with a GET request triggered by a standard <a> tag. Once the authentication is successf ...

Are the functions 'useEffect' and 'useCallback' being repetitively used in this case?

I have implemented a custom hook in my React application to manage back navigation actions (POP). The functionality is operational, but I can't help but notice that useCallback and useEffect seem to be performing similar tasks. Here is the snippet of ...

The FirebaseX Ionic native plugin received 2 arguments instead of the expected 3-4

Trying to implement Firebase Phone Auth with the FirebaseX plugin, I encountered an issue. Here is the code snippet I used: async getVerificationCode(): void { const res:any = await this.firebaseX.verifyPhoneNumber('+16505553434', 60); ...

Can the inclusion of a type guard function impact the overall performance of the application?

const typeGuard = (param: any): param is SomeType => { return ( !!param && typeof param === "object" && param.someProperty1 !== null && param.someProperty2 === null ) } If a type guard function similar to the code above is exe ...

random mongoose response 500

I came across a nodeJS code recently that was supposed to retrieve random documents from my mongoose collection using the mongoose-random plugin. However, whenever I call the findRandom() method, it returns a 500 error. test.js Below is the code snippet: ...

The Node.js express seems to be unable to fetch the css and js files

Sharing my main.ts file in which I am facing issues with linking my css and js files. view image import express from 'express'; import {Request,Response} from 'express'; import expressSession from 'express-session'; import pat ...

Using Angular2's NgFor Directive in Components

I am faced with the challenge of converting a tree-like structure into a list by utilizing components and subcomponents in Angular 2. var data = [ {id:"1", children: [ {id:"2", children: [ {id: "3"}, {id: "3"}, {i ...

``If you're looking to integrate a 360-degree product viewer into your Angular application, here is a

I am in need of showcasing a 360 Product viewer consisting of an array of 36 car images in base64 format. Despite attempting to utilize the angular-three-sixty Package by @mediaman, I was only met with an empty canvas. Does anyone have experience in implem ...

Issues have been encountered with Angular 5 when trying to make required form fields work properly

Just created my first Angular app using Angular 5! Currently following the documentation at: https://angular.io/guide/form-validation. Below is the form I have set up: <form class="form-container"> <mat-form-field> <input matInput pl ...