Converting Dates to Strings and Validating Arrays in Nest.js DTOs

Whenever I send a JavaScript Date() object through a put request to my Nest backend, I expect the date format to remain unchanged. However, it gets passed as a string, making it quite challenging to manage. I attempted using DTOs, but encountered an issue where the data is nested within an array. Can the DTO be applied to interfaces as well?

Here's what I currently have:

OpeningHoursInterface.ts

export interface OpeningHoursInterface {
    dayOfWeek: number,
    open: Date,
    close: Date,
    isOpen: boolean
}

DTO.ts

import { IsArray, IsObject, IsString, ValidateNested } from "class-validator";
import { CnmInterface } from "../interfaces/cnm.interface";
import { OpeningHoursInterface } from "../interfaces/openingHours.interface";

export class UpdateCnmDto {

    @IsString()
    _id: string;

    @IsObject()
    cnm: CnmInterface;

    @IsArray()
    @ValidateNested({ each: true })
    openingHours: [OpeningHoursInterface]

}

controller.ts

  @UseGuards(JwtAuthGuard)
  @Put('')
  @UsePipes(new ValidationPipe({ transform: true }))
  async updateCnm(@Body() updateCnmDto: UpdateCnmDto, @GetUser() user: UserInterface) {
    console.log("update cnm in controler", updateCnmDto)
    return await this.storesService.updateCnm(updateCnmDto, user)
  }

UPDATE 2021-03-28:

Thank you for your response!

I am encountering the following error in my console:

error TS1128: Declaration or statement expected.

Within VS Code, I see the ts(2693) error which mentions that "OpeningHoursInterface" is connected to a type but being used as a value.

I attempted to modify my tsconfig.json:

{
  "compilerOptions": {
    "module": "commonjs",
    "declaration": true,
    "removeComments": true,
    "emitDecoratorMetadata": true,
    "experimentalDecorators": true,
    "allowSyntheticDefaultImports": true,
    "target": "es2017",
    "sourceMap": true,
    "outDir": "./dist",
    "baseUrl": "./",
    "incremental": true
  }
}

Your assistance is greatly appreciated.

Answer №1

To implement the @Type annotation from the library known as 'class-transformer', make sure you are using a class and not an interface. This is necessary for proper instantiation by class-transformer.

@IsArray()
@ValidateNested({ each: true })
@Type(() => OpeningHours)
openingHours: [OpeningHours]

Similarly, apply the following within the OpeningHours class:

@Type(() => Date)
open: Date

@Type(() => Date)
close: Date

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

A custom type in Typescript used as a key in a key-value pair

Here is a key-value pair used for a filtering system. The filter can be merged with current filters or applied by resetting the previous ones. type MINE = "mine" type BOOKMARKED = "bookmarked" type TEXT_QUERY = "textQuery" typ ...

Arranging Select Dropdown Options in a Specific Order using Angular 7 and Typescript

My select dropdown is populated dynamically with options fetched from a service using *ngFor. I am looking to customize the order of these options. Can this be achieved through Angular code? The array structure is as follows: console.log(this.paymentTyp ...

Include an additional value to the existing array

Here is the code snippet I am working with: $result = array(); $category_name = array(); foreach($category as $cat) { $category_name[] = $cat->category_name; // This value needs to be added to the result array $campaigns = $cat-> ...

How can you transform a multi-dimensional array into HTML input fields?

I have a task where I need to convert a multidimensional array into HTML form fields. Here is an example of what I'm trying to achieve: <input type="hidden" name="c_record[contact][0][name]" value="First Last"> <input type="hidden" name="c_r ...

Is there a method `Object.values()` available in TypeScript?

How can I iterate through all values of an Object in TypeScript that I want to use for filtering another array? I have searched on Google and came across Object.values(), but it seems like it doesn't work in TypeScript. Is there an equivalent method ...

Obtain the string representation of an array located on a remote server

I am facing a challenge in extracting the content of an array from a remote server. The restrictions in the PHP implementation of xmlrpc allow me to only send back strings, eliminating the possibility of using var_dump(). I attempted to use var_export, but ...

"I am looking for a way to incorporate animation into my Angular application when the data changes. Specifically, I am interested in adding animation effects to

Whenever I click on the left or right button, the data should come with animation. However, it did not work for me. I tried adding some void animation in Angular and placed a trigger on my HTML element. The animation worked when the page was refreshed, bu ...

Implementing multiple TypeScript classes with the same interface and comparing the properties of their objects

Looking to incorporate 2 classes for business logic within my application. Below is some pseudo code showcasing the use of object and string types to specify each logic: Includes interface and class declarations; interface IResult<T, E> { resul ...

The inference of optional generic types is not occurring

I need help addressing a type error in my TypeScript wrapper for handling NextJS API requests. Specifically, I am facing an issue when trying to pass a single type for one of the generic types in the function. To illustrate this error, I have created a si ...

What is the best way to simulate an observable variable in a unit test?

I am currently in the process of learning how to write unit tests. The following code snippet is part of the coursework that I am studying: #spec.ts ... beforeEach(waitForAsync(() => { const coursesServiceSpy = jasmine.createSpyObj("Cours ...

Angular 11 is causing confusion by incorrectly applying the Http interceptor to sibling modules

Here is the structure of my modules: https://i.sstatic.net/zO9dE.png The HTTP interceptor I provided in core.module.ts is affecting the HTTP client in the translation.module.ts. This is how my core module is set up: @NgModule({ declarations: [DefaultLa ...

When you find that the plugins on pub.dev do not offer web support, consider utilizing npm packages for Flutter web development

I am currently working on developing a cross-platform app using Flutter for iOS, Android, and web. However, some plugins do not support web. Fortunately, I came across npm packages that provide the same functionality and I am considering integrating them. ...

Get notified about the number of cells you've selected by simply dragging on a table

Is there a way to display the number of selected cells in a table when dragging with the mouse? I have a table set up, and I'd like to create an alert that shows how many cells are selected while dragging. Here is the link to my fiddle: http://jsfiddl ...

Attempting to deactivate the submit button in the absence of any input

As a beginner trying to work with typescript and html, I am facing an issue with disabling the submit button when a user fails to enter a part number. The error message I am getting is "Cannot find name 'partNumber'". Any advice or guidance on th ...

Leveraging non-ionic-native Cordova plugin

I'm currently working on integrating the [This]https://github.com/louisbl/cordova-plugin-locationservices plugin into my Ionic 4 app. Since it's a non-Ionic-native plugin, what is the proper way to call its functions within my TypeScript code? ...

A guide to tallying repeated numbers in an ordered array

I've been working on a problem that involves reading values from a file into a program and then outputting those values along with their average, minimum, maximum, and the number of times each unique value appears. I'm struggling with creating an ...

Update information according to the drop-down choice made from a different, unrelated component in Angular

I have different components that are not related. When I select a company from the header component, I want to immediately display data that matches the selected company. Currently, the data changes only when I visit another page and then return, but I nee ...

Java Odd Scenario: Mooc Helsinki Part 1 Week 4 Exercise 18

Encountering a challenging issue with an error that seems to be stumping me completely. FAIL: PersonalInformationCollectionTest testInputFirst Something strange has occurred. It appears that the void main (String[] args) method of the class PersonalInform ...

Executing vitest on compiled javascript files

Currently facing issues running vitest on compiled JavaScript. Numerous errors are appearing, such as: TypeError: Cannot read properties of undefined (reading 'spyOn') TypeError: Cannot read properties of undefined (reading 'mock') and ...

Is it possible to resize without defining dimensions?

Currently, I am working with Access 2010 on Win7. I have recently discovered that I can dynamically size my arrays at runtime simply by using ReDim arrayName(x) without having to declare the array with Dim arrayName() first. Sub FooBar() ReDim myArray( ...