Ignore any information in NestJS that is not included in the data transfer object

In my NestJS controller, I have defined a route for updating locality information. The structure of the controller method is as follows:

@Put('/:id')
  updateLocalityInfo(
    @Query('type') type: string,
    @Body() data: EditLocalityDto,
    @Body('parentId', ParseIntPipe) parentId: number,
    @Param('id', ParseIntPipe) id: number,
  ) {
    console.log(data);
    return this.localitiesService.updateLocalityInformation(
      type,
      data,
      id,
      parentId,
    );
  }

While working with this route, I encountered an issue related to the Dto and the parentId variable. It appears that when I call the route, the parentId value is included in the Dto-data. Upon logging the data, I observed the following output:

{ name: 'exampleName', parentId: '1' }

The EditLocalityDto class, however, only contains a property for the name:

import { ApiProperty } from '@nestjs/swagger';

export class EditLocalityDto {
  @ApiProperty()
  name: string;
}

I am seeking a solution to remove the parentId from being part of the dto-data. How can I achieve this adjustment in a general context?

Answer №1

Consider two different approaches for this:

Option 1

To eliminate the redundant property using TS from the DTO:

@Put('/:id')
  updateLocalityInfo(
    @Query('type') type: string,
    @Body() { parentId: _, ...data }: EditLocalityDto,
    @Body('parentId', ParseIntPipe) parentId: number,
    @Param('id', ParseIntPipe) id: number,
  ) {
    console.log(data);
    return this.localitiesService.updateLocalityInformation(
      type,
      data,
      id,
      parentId,
    );
  }

Option 2

Rather than excluding the property, consider adding it to the DTO itself and validating it there:

@Put('/:id')
  updateLocalityInfo(
    @Query('type') type: string,
    @Body() { parentId, ...data }: EditLocalityDto,
    @Param('id', ParseIntPipe) id: number,
  ) {
    console.log(data);
    return this.localitiesService.updateLocalityInformation(
      type,
      data,
      id,
      parentId,
    );
  }

///

import { ApiProperty } from '@nestjs/swagger';

export class EditLocalityDto {
  @IsInt()
  parentId: number

  @ApiProperty()
  name: string;
}

I personally prefer the latter approach

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

Tips on preventing the need for null or undefined checks in JS/Typescript singletons that have an initialization function

Is there a way to streamline the process of handling props in an Object literal that is dynamically initialized only once? I'm looking for a pattern that would eliminate the need for repetitive null/undefined checks and throw errors when certain metho ...

Typescript does not directly manipulate values. For instance, using a statement like `if(1==2)` is prohibited

I am currently developing an Angular application with a code coverage report feature. There is a method where I need to skip certain lines based on a false condition. So, I attempted to create a function in my component like this: sum(num1:number,num2:nu ...

The Google Chrome console is failing to display the accurate line numbers for JavaScript errors

Currently, I find myself grappling with debugging in an angular project built with ionic framework. Utilizing ion-router-outlet, I attempt to troubleshoot using the Google Chrome console. Unfortunately, the console is displaying inaccurate line numbers mak ...

Eliminating an element from an object containing nested arrays

Greetings, I am currently working with an object structured like the following: var obj= { _id: string; name: string; loc: [{ locname: string; locId: string; locadd: [{ st: string; zip: str ...

Tips for extracting data from an Angular object using the *ngFor directive

https://i.stack.imgur.com/ai7g1.png The JSON structure displayed in the image above is what I am working with. My goal is to extract the value associated with the key name. This is the approach I have taken so far: <span *ngFor="let outlet of pr ...

Tips on identifying and handling errors without the need for type assertions in this code segment

My code is correct, but it's becoming difficult to maintain... interface FuncContainer<F extends (..._: Array<any>) => any> { func: F args: Parameters<F> } const func: FuncContainer<typeof Math.min> = { func: Math.min ...

Encountering an error in Chrome where the property 'command' is undefined

Currently utilizing typescript and encountered an error in the chrome console: Error found in event handler for (unknown): TypeError: Unable to access property 'command' as it is undefined at chrome-extension://somethingsomethingsometh ...

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 ...

Angular 2 does not recognize the existence of .then in type void

I have a query regarding Angular2 and I'm struggling with the void function in my code. Can someone help me out? I am new to Angular2 and unsure of what needs to be added in the void function. Check out this image for reference export class PasswordR ...

Issue with Formgroup in Angular Reactive Form - Validation not functioning as expected

I am working with a form group which is defined below: get createItem(): FormGroup { return this.formBuilder.group({ name: ['', Validators.required], email: ['', Validators.required], mobile: ['', V ...

Due to a TypeScript error stating that the type '{ Id: number; Name: string; }' cannot be utilized as an index type, I am unable to assign a value for students at this time

I am facing an issue with defining a value for students in TypeScript. It is giving me an error saying that it can't be used as index type. Just to clarify, I have declared id as number (not Number) and Name as string (not String). import { Component ...

Guide on Reacting to an Occurrence in Angular

I have a scenario where an event is triggered every 10 seconds. After subscribing to the event on the receiving end, I need to figure out how to send data back to the class responsible for emitting the event. constructor(@Inject(ABC.XYZ) private events: ...

When the route changes, routerCanReuse and routerOnReuse are not invoked

I am currently exploring the functionalities of Angular2's Router, specifically focusing on OnReuse and CanReuse. I have followed the documentation provided here, but I seem to be encountering difficulties in getting the methods to trigger when the ro ...

How can I assign a specific class to certain elements within an *ngFor loop in Angular?

I have a situation where I am utilizing the *ngFor directive to display table data with the help of *ngFor="let record of records". In this scenario, I am looking to assign a custom CSS class to the 'record' based on specific conditions; for exam ...

Vue: Simple ways to retrieve state data in MutationAction

I'm having trouble accessing the state inside @MutationAction Here is the setup I am using: Nuxt.js v2.13.3 "vuex-module-decorators": "^0.17.0" import { Module, VuexModule, MutationAction } from 'vuex-module-decorators' ...

Why am I unable to retrieve the property from the JSON file?

Below is the provided JSON data: data = { "company_name": "חברה לדוגמה", "audit_period_begin": "01/01/2021", "audit_period_end": "31/12/2021", "reports": [ ...

Learn the technique for dynamically modifying Angular components within the main root component during runtime

I am looking to incorporate a dynamic form where the configuration button triggers the switch from app-login-form to login-config-form. app.component.html <div class="container p-5"> <app-login-header></app-login-header> <div cla ...

The Angular Material Table is reporting an error: the data source provided does not conform to an array, Observable, or DataSource

Having some trouble with an Angular Material table, as I'm encountering an error preventing me from populating the grid: Error: Provided data source did not match an array, Observable, or DataSource search.service.ts GridSubmittedFilesList: IGridMo ...

Connecting Multiple Relationships with Many-To-Many Matches

My database consists of the following entities: @Entity class User { @ManyToMany(type => Group) @JoinTable() groups: Group[]; } @Entity class MediaObject { @ManyToMany(type => Group) @JoinTable() groups: Group[]; } @Entity ...

What methods are available to expedite webpack compilation (or decouple it from server restart)?

My current setup includes the following configurations: import path from 'path' import type {Configuration} from 'webpack' const config: Configuration = { mode: 'development', entry: path.join(__dirname, '../..&apos ...