Dealing with Nested Body Payload in PATCH Requests with Constructor in DTOs in NestJS

Within my NestJS environment, I have constructed a DTO object as follows:

export class Protocol {
  public enabled?: boolean;
  public allowed?: boolean;
  constructor(enabled: boolean, allowed: boolean) { // With a necessary constructor
    this.enabled = enabled;
    this.allowed = allowed;
  }
}

Now, my goal is to utilize this same Protocol within a RequestDTO for my PATCH request. This can be achieved like so:

In the Controller:

  modifySomething(@Param('id') id: string, @Param('uuid') uuid: string, @Body() body: ModifyRequest) {
    return this.service.modify(id, uuid, body);
  }

Defined in my DTO (ModifyRequest):

export class Protocol {
  public enabled?: boolean;
  public allowed?: boolean;
  constructor(enabled: boolean, allowed: boolean) { // With a necessary constructor
    this.enabled = enabled;
    this.allowed = allowed;
  }
}

export class ModifyRequest {
  public name?: string;
  public nfs?: Protocol;
}

The question at hand now becomes:

How do I accurately map the incoming request @Body to this DTO object? Here are some strategies I've explored prior to seeking assistance:

  1. If the constructor is removed, the mapping functions correctly. However, removing it is not an option due to other dependencies.
  2. I attempted to use class-transformer, implemented as follows:
   import { Type } from 'class-transformer';
   export class ModifyRequest {
      public name?: string;
      @Type(()=>Protocol)
      public nfs?: Protocol;
   }

Unfortunately, this approach did not yield the desired results.

Any guidance on achieving this dual use of Protocol within both Response (which necessitates a constructor) and RequestDTO would be greatly appreciated.

nestjs

Answer №1

Here is my solution using the class-transformer library:

   import { Type } from 'class-transformer';

   export class ModifyRequest {
      public name?: string;
      @Transform(({ value }) => {
         return new Protocol(value.enabled, value.allowed);
      })
      public nfs?: Protocol;
   

Success!

I wonder if there are any alternative methods to handle this scenario with class-transformer without needing to create a new instance. If you have any insights, please share them with me.

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

When using html2canvas in Angular, it is not possible to call an expression that does not have a call signature

I'm currently working on integrating the html2canvas library into an Angular 8 project. Despite trying to install the html2canvas types using npm install --save @types/html2canvas, I'm still facing issues with its functionality. Here's how ...

Encountering issues with Next.js routing - Pages failing to load as expected

Having some trouble with the routing in my Next.js application. I've created a page named about.tsx within the "pages" directory, but when trying to access it via its URL (localhost:3000/about), the page fails to load correctly and displays: This Pa ...

Tips for implementing react-select types in custom component development

Currently, I'm in the process of developing custom components for DropdownIndicator to be used on react-select with Typescript. However, I am encountering difficulties with the component's type due to my limited experience with Typescript. I wou ...

What is the meaning of '=>' in typescript/javascript?

I keep coming across lots of '=>' in the code I found on the internet. Could someone please explain it to me as if I were 5 years old? (I'm searching for the specific code, and I'll share it here once I locate it).. Found it: ...

"Encountering issues when trying to retrieve a global variable in TypeScript

Currently facing an issue with my code. I declared the markers variable inside a class to make it global and accessible throughout the class. However, I am able to access markers inside initMap but encountering difficulties accessing it within the function ...

Tips on customizing the selected icon color in Material-UI's BottomNavigationAction styling

I'm facing an issue with Material-UI styled components and could use some assistance. My goal is to create a BottomNavigation bar in React using Material-UI v5 where the selected option's icon displays in red (#f00) while the unselected icons sho ...

Unable to generate or compose a text document within my Ionic application

After attempting to create a file and write in it, I'm encountering an issue where the file appears to be created but is not visible when navigating to the folder. Can someone please point out what might be going wrong? Below is my code snippet: th ...

A guide on connecting multiple select components to a unified Angular 6+ reactive form without triggering redundant updates

I am facing an issue where I need to connect multiple input components to a single angular reactive form, but encounter two main obstacles: By default, only the form in which user input occurs gets updated If I use [(ngModel)] it does work, but it trigge ...

What is the process for sending an http get request that provides a JSON array to populate an ngFor directive?

I'm trying to figure out how to make an http get request in order to retrieve a json array of data that I can use within an ngFor loop. The list that needs to be looped through is stored in this.list. Currently, the json file for testing purposes is l ...

Error in Angular 5: Google Maps not defined

Having trouble implementing Google Maps on my Angular 5 app. Upon loading the view, I am encountering this error in the JavaScript console: LoginComponent_Host.ngfactory.js? [sm]:1 ERROR ReferenceError: google is not defined at LoginComponent.ngAfterVie ...

An Angular module downloaded from npm seems to be lacking the required @NgModule declaration

There seems to be a missing @NgModule and @Directive declarations in an NPM module, even though they exist in the source code on Github. This is causing an issue with importing a directive for databinding from an HTML attribute. I am attempting to utilize ...

What is the process for creating an additional username in the database?

As a beginner frontend trainee, I have been tasked with configuring my project on node-typescript-koa-rest. Despite my best efforts, I encountered an error. To set up the project, I added objection.js and knex.js to the existing repository and installed P ...

Changing a password on Firebase using Angular 5

I am in the process of developing a settings feature for user accounts on an application I've been working on. One key functionality I want to include is the ability for users to update their password directly from the account settings page. To enable ...

Error encountered in Jest mockImplementation: Incompatible types - 'string[]' cannot be assigned to 'Cat[]' type

Recently, I've been writing a unit test for my API using Jest and leveraging some boilerplate code. However, I hit a snag when an error popped up that left me scratching my head. Here is the snippet of code that's causing trouble: describe(' ...

The data type 'string | undefined' cannot be assigned to the data type 'string' when working with .env variables

Trying to integrate next-auth into my nextjs-13 application, I encountered an error when attempting to use .env variables in the [...nextauth]/route.ts: Type 'string | undefined' is not assignable to type 'string'. https://i.stack.im ...

Is there a way to end my session in nextAuth on NextJS 14?

Recently, I've started using Typscript with a NextJS14 project that utilizes NextAuth for authentication. While there weren't any errors in the JavaScript version of my code, I encountered an error when working with TypeScript. This is a snippet ...

Describe a Typescript Interface Value as a collection of strings or any input provided as an argument

Uncertain if the question title is accurate - currently developing react components within a library that has specific predefined values for certain properties. However, additional values may need to be added on a per usage basis. So far, this setup is fun ...

A guide on how to follow a specific item in an Angular 2 store

I have integrated ngrx store into my Angular2 application. The store reducer contains two objects as shown below: export function loadSuccessNamesAction(state: StoreData, action: loadSuccessNamesAction): StoreData { const namesDataState = Object.assi ...

Unable to extract the 'data' property from an undefined source in React, causing an error

I encountered this error message: TypeError: Cannot destructure property 'data' of '(intermediate value)' as it is undefined. export const getServerSideProps: GetServerSideProps = async () => { // categories const { data: categor ...

NestJS Bull queues - Failing to secure job completion with a lock

I am currently utilizing Bull in combination with NestJS to manage a jobs queue. Within the process handler, I aim to designate a job as failed instead of completed. However, it appears - after carefully reviewing the documentation as well - that the Job#m ...