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

The function is failing to return the expected value received from the observable subscription

I am attempting to verify the existence of a user in an Angular's in-memory API by validating their username. The function checkUsernameExists(username) is supposed to return an Observable<boolean> based on whether the API responds with undefine ...

Simulation service agent partnered with openApi backend

I am currently utilizing MSW along with the OpenAPI-backend package for my project. I aim to mock both the browser server and test server using OpenAPI specifications. With an available OpenAPI definition, I generate `generated.ts` for RTK Query (which is ...

I'm encountering an issue where the database table in Postgres is not updating correctly while working with Node

Currently, I am working on a CRUD application where I can successfully read and delete data from the database table. However, I have encountered an issue when trying to update specific data for a particular route. Every time I attempt to update the data in ...

I'm looking to extract various data from a SQLite table using the URL with ExpressJS. What's the best way to achieve

I need to access data from a SQLite database table that contains information on accounts, movies, and reviews. Specifically, the structure of the reviews-table is as follows: CREATE TABLE IF NOT EXISTS reviews ( id INTEGER PRIMARY KEY, authorId INT ...

Messages sent to RabbitMQ through amqplib are not being received in the reply queue, even after being processed by NestJS

Currently, I am utilizing NestJS (v8) in combination with the RabbitMQ transport (Transport.RMQ) to receive messages. The code structure within my NestJS application appears as follows: // main.ts const app = await NestFactory.createMicroservice<Micro ...

Executing a function in the constructor of an Angular4 component

I am currently facing an issue where I am attempting to invoke a modal function within the constructor in Angular 4. However, it seems that the function is not being called properly as it gets highlighted. Upon loading the page, no errors are logged and th ...

What is the best way to transfer image files into a specific folder?

I am currently in the process of developing a ReactJS web application. My goal is to upload images to a specific folder and then store the file name in the database for future use. Everything seems to be working smoothly up to this point, but I am facing ...

Is there a way to specify patternProperties in a JSON schema and then map it to a TypeScript interface?

I'm in the process of developing a TypeScript interface that corresponds to a JSON schema. The specific field in my JSON schema is as follows: "styles": { "title": "Style Definitions", &qu ...

Should the use of readFileSync() during the initialization of a Node.js web application be avoided?

I have a Node app that serves web pages with static HTML-snippet files included conditionally. I am considering implementing a cache map for these snippets by adding the following code to my Express's app.js file: var cache = Object.create(null); cac ...

How can I send a curl request to node.js server but receive a 200 JSON response from server.js?

I have set up a notification system on node.js and I am trying to push notifications to it using curl in PHP. However, when I use curl in either terminal or PHP, it doesn't return anything but the notification is successfully pushed. How can I modify ...

Identifying asynchronous JavaScript and XML (AJAX) requests using Express in NodeJS

When working with NodeJS and Express, I am wondering how to distinguish between a regular browser request and an AJAX request. I understand that one approach is to inspect the request headers, but I am curious if Node/Express provides direct access to th ...

Vue.js 3 with TypeScript is throwing an error: "Module 'xxxxxx' cannot be located, or its corresponding type declarations are missing."

I developed a pagination plugin using Vue JS 2, but encountered an error when trying to integrate it into a project that uses Vue 3 with TypeScript. The error message displayed is 'Cannot find module 'l-pagination' or its corresponding type ...

JavaScript: Trouble accessing .target property for click event in EventTarget object

After converting my project from regular JavaScript to TypeScript, I encountered an issue where the target property of a base class EventTarget was not being recognized by TypeScript. This property worked perfectly fine in JS, so it must exist. Could it be ...

In Typescript, null values are allowed even when the type is set to be non-nullable

Can someone explain why the code below allows for null in typescript, even though number is specified as the type: TS playground // Not sure why null is accepted here when I've specified number as the type const foo = (): number => 1 || null ...

Using a Typescript enum as a parameter type can lead to accepting incorrect values

When working with TypeScript, I have defined an enum, and now I want to create a function that accepts a parameter whose value is one of the enum's values. However, TypeScript does not validate the value against the enum, allowing values outside of th ...

cors library returns success messages, not errors

Currently, I am working on implementing the cors package within a node and express environment to validate whether the requesting domain can access my resources. Setting up the validation part following the official documentation was not an issue. However, ...

The Ubuntu virtual machine hosted on Google Cloud is experiencing difficulties connecting through Node.js using an external IP address

const express = require('express'); const bodyParser = require('body-parser'); const path = require('path'); const app = express(); app.listen(3000, function(){ console.log('Server is now live on port 3000' ...

auth.js:15 Caution: The update depth has reached its maximum limit. This issue may arise if a component triggers setState within useEffect

I am facing an issue with React rendering infinitely and I am not sure how to stop it. Can someone provide a solution for the code attached below? Error displayed in console: """ [1836] auth.js:15 Warning: Maximum update depth exceeded. Th ...

What is the best way to avoid passing a value to a component in nextjs?

I'm trying to make this component static and reusable across different pages without passing a parameter when calling it. Is there a way to achieve this while following the official documentation? component: import { GetStaticProps, InferGetServerSid ...