What is the best way to implement a decorator for a class method variable within a NestJS framework?

import {isNotEmpty} from "class-validator";

export Service   {

create(createdto)
{
const {name,age} = createdto;

@isNotEmpty()
name          //applying a decorator to ensure name is not null or undefined
} 
}

As the decorator is designed for class methods, it cannot be applied to method variables directly. Is there a way to validate these variables?

Answer №1

Due to the lack of support for decorators on local variables in ECMAScript2016/Typescript, it is not possible to use decorators in the service as described in the question.

However, class-validator offers a non-decorator implementation for its validation functions.

The class-validator Github page states: https://github.com/typestack/class-validator#manual-validation

The Validator has various methods that allow non-decorator based validation:

import { isEmpty, isBoolean } from 'class-validator';

isEmpty(value); isBoolean(value);

Therefore, the same goal can be achieved with code similar to this:

import { Injectable } from "@nestjs/common";
import { CreateDto } from "./dto/create.dto";
import { isEmpty, isInt } from "class-validator";

@Injectable()
export class TestValidationService {
  test(createDto: CreateDto) {
    const {name, age} = createDto;
    
    if (isEmpty(name)) {
      throw "There is no name.";
    }
    
    if (!isInt(age)) {
      throw "Age is not int."
    }
    
    return createDto;
  }
}

If you prefer not to use individual methods within the service, you can still decorate your DTO and use the validate method from class-validator.

For example:

import { IsInt, IsNotEmpty } from "class-validator";

export class CreateDto {
  @IsNotEmpty()
  name: string;
  
  @IsInt()
  age: number
}

And in your service:

async testWithValidate(createDto: CreateDto) {
    const validationResult = await validate(createDto);
}

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

I'm having trouble with the routing of a Node.js REST API built with Express and Mongoose

I am currently in the process of constructing a RESTful webservice by following a tutorial that can be found at: However, I have encountered an issue where it is returning a CANNOT GET/ reports error. Despite my efforts to troubleshoot and rectify the pro ...

Having trouble integrating Azure with my Ionic2/Angular2/Cordova app

I am currently developing with the Ionic2 Blank app template. I encountered an issue when trying to set up Azure using the following line of code in home.ts: import azureMobileClient from 'azure-mobile-apps-client'; . The deployment process wen ...

Replacing the '+' character with a space in HttpParams within Angular 6

When passing a JSON object using HttpParams, the + character is automatically converted to a space before being sent to the backend. Despite trying multiple solutions, I have been unable to resolve this issue for a JSONObject string. this.updateUser({"nam ...

Integrating information from various sources to create a cohesive online platform

I am looking to incorporate data from various sources into a single web page: Social networks (Facebook, Twitter, LinkedIn, etc.) RSS feeds Article meta tags (particularly OpenGraph and Twitter cards) This data may change dynamically based on user inter ...

Error in Angular TypeScript occurs when attempting to read properties of an undefined value

Here is the interface that I am working with: export interface IQuest { Id: number, lat: number, lon: number, Question:string, Answer:boolean, IsDone:boolean, Correct:boolean, Range:number} Along with the following component: export class AppComponent imp ...

I am experiencing an issue with the checkbox in my React app where the state is not updating after it has been

I am currently building a todo app using React, but I'm encountering an issue where nothing happens when I click the checkbox. I've provided my code below: App.js import './App.css'; import React from 'react' import TodoItem ...

The GridFS/multer module is encountering an issue where it is unable to access the 'filename' property of an undefined

My knowledge in web development is limited, so forgive me if this question seems naive. The issue I am facing involves Node.Js and the creation of a database to store and display images on a browser using an .ejs file. While I can successfully log the im ...

Decode array in JavaScript

Hello, I'm currently trying to deserialize this array in JavaScript using the PHPunserialize module: a:7:{s:13:"varPertinence";a:4:{i:0;s:5:"REGLT";i:1;s:2:"13";i:2;s:2:"15";i:3;s:2:"16";}s:10:"varSegment";N;s:12:"varSSegment1";N;s:12:"varSSegment2"; ...

Tips for adjusting the size of an imported item in Three.js?

Currently, I am utilizing Three.js for my project and I am importing .OBJ file using OBJ LOADER () Everything has been working smoothly thus far, but I have come across an issue that has me stumped. I am trying to figure out how to change the width and he ...

Struggling to fix the npm install pre-gyp error

I'm currently in the process of setting up this application on my m1 MacBook Air > Github - Todoist Clone When I run npm install in the terminal, I encounter the following error. Please refer to the log below: 10630 verbose node v16.13.2 10631 ver ...

choose a value from a dropdown menu to reset other dropdowns to their default values

I am encountering an issue with my PHP form that consists of 7 dropdown lists. Whenever I select a value from one of the dropdown lists, I want the other 6 to reset to their default values if they were previously opened. I believe using JavaScript is neces ...

Unexpected behavior: Angular4/Javascript Date object alters when timezone is specified in Date constructor

In my Angular 4 application, I encountered an issue with a date retrieved from an API call. The date is in the format '1990-03-31T23:00:00-06:00' and when attempting to create a Date object and retrieve the month using getMonth(), it returns the ...

Updating padding through local storage does not function as intended

I recently added two buttons to my website for adjusting the padding. While they are functional, I find myself manually setting the padding for nav, main, and footer in the CSS. Here is the snippet of the code: main { padding: 20px 25%; } footer { ...

Converting base64 dataUrls into images using typescript

When using ng2-image cropper, it does not accept the "src" attribute and instead requires the "image" attribute. As a result, if a dataUrl is provided, the image will not display in the cropper. I am utilizing the camera to capture an image and obtaining ...

Create a dynamic AppBar Toolbar in React Admin that changes based on the current page

Recently delving into the world of React, I've been facing some challenges when it comes to loading IconButtons onto the toolBar of an AppBar (from Material UI). For instance, I'm looking to have two specific IconButtons displayed on pageA and d ...

In Angular 5, you cannot assign type 'any[]' to type 'typeof User'

After extracting data from the JSON file, I encountered a typo error message stating: Type 'any[]' is not assignable to type 'typeof User'. Here is my code in app.component.ts: import { Component, OnInit } from '@angular/core&a ...

Instructions for activating and deactivating a numerical input field with a checkbox

Is there a way to create a pair of a checkbox and number field that are linked together? When the checkbox is clicked, it should disable the associated number field. Javascript File: $(document).ready(function(){ $("input[name=check]").click(function(){ ...

Can an iframe be replicated?

How can I retrieve the content of a specific webpage, such as http://google.com, and dynamically insert it into the current document while preserving styles, scripts, and other elements just like an iframe does? Additionally, I want to ensure that the sty ...

Retrieve records with at least one connection, but display all of them

After creating this entry, it now consists of 2 tags - tag1 and tag2. { "id": "d87de1d9-b048-4867-92fb-a84dca59c87e", "name": "Test Name", "tags": [ { "id": "fa0ca8fd-eff4-4e58-8bb0-a1ef726f01d4", "name": "tag1", "organizationI ...

Loop through an array that holds another array in javascript

After making a post request, I am receiving the following object: "{\"Success\":false,\"Errors\":{\"Name\":[\"The Name field is required.\"],\"Id\":[&b ...