Exploring the concept of using a single route with multiple DTOs in NestJS

At the moment, I am utilizing NestJS for creating a restful API. However, I am currently facing an issue with the ValidationPipe. It seems to only be functioning properly within controller methods and not when used in service methods.

My goal is to implement different DTO classes (UserCreateDTO, StaffCreateDTO,...) based on the specific ROLE (admin, staff, user) associated with a particular route.

Answer №1

Pipes are only suitable for use in controllers and cannot be used with services. However, you can utilize the validate method from class-validator (alongside the plainToClass method from class-transformer) anywhere within your code:

const user = plainToClass(UserCreateDto, userRequestEntity);
const errors = await validate(user)
if (errors.length > 0) {
  throw this.createError(errors);
}

Furthermore, there is no requirement to create distinct DTO classes for various roles. Simply leverage class-validator groups:

Assign each property in your DTO to one or more groups (= roles):

@Min(12, {groups: ['admin', 'staff']})
age: number;
@Length(2, 20, {groups: ['admin']})
name: string;

Then provide your group (roles) to plainToClass and validate.

// Provide your roles as groups
const groups = ['admin'];

// Convert to class with groups
const entityClass = plainToClass(EntityDto, entity, { groups })

// Validate with groups
const errors = await validate(entityClass, { groups });

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

Enhancing TypeScript Modules

Recently, I encountered an issue with my observable extension. Everything was functioning perfectly until I updated to angular 6 and typescript 2.7.2. import { Observable } from 'rxjs/Observable'; import { BaseComponent } from './base-compo ...

Automatic browser refresh with the `bun dev` command

Currently experimenting with the latest bun platform (v0.1.6) in conjunction with Hono. Here are the steps I followed: bun create hono test-api cd test-api bun dev After running the server, the following message appears: $ bun dev [1.00ms] bun!! v0.1.6 ...

Function in Typescript that accepts either a single object or an array of objects

We frequently use a simple function declaration where the function can accept either a single object or an array of objects of a certain type. The basic declaration looks like this: interface ISomeInterface { name: string; } class SomeClass { pu ...

Wondering how to implement HubSpot Conversations SDK in a Typescript/Angular application?

Recently, I came across some useful javascript code on this website window.HubSpotConversations.widget.load(); window.HubSpotConversations.widget.refresh(); window.HubSpotConversations.widget.open(); window.HubSpotConversations.widget.close(); Now, I am l ...

`Browser Extension Compatibility``

I am currently working on developing a TypeScript extension that is compatible with all major browsers. I have come across the package https://www.npmjs.com/package/web-ext-types which I have integrated into my package.json file. While coding in TypeScrip ...

Utilize Angular 5 to implement URL routing by clicking a button, while also preserving the querystring parameters within the URL

I have a link that looks like this http://localhost:4200/cr/hearings?UserID=61644&AppID=15&AppGroupID=118&SelectedCaseID=13585783&SelectedRoleID=0 The router module is set up to display content based on the above URL structure { path: & ...

What steps can be taken to delay information transmission until a secure password is chosen?

I have implemented the PasswordStrengthBar component. How can I ensure that the request is not sent until a strong password is entered? Essentially, I want to prevent the request from being sent if the password is weak. I am using the useForm hook. < ...

Is it possible to showcase a variety of values in mat-select?

Is it possible to pass different values to the .ts file in each function? For example, can I emit a String with (selectionChange)="onChangeLogr($event)" and an object with (onSelectionChange)="onChangeLogr_($event)"? How would I go about doing this? ...

The value from select2 dropdown does not get populated in my article in Angular

I am attempting to link the selected value in a dropdown menu to an article, with a property that matches the type of the dropdown's data source. However, despite logging my article object, the property intended to hold the selected dropdown value app ...

Is there a way to ensure DRY principles are followed while utilizing Redux Toolkit's asyncThunkCreator?

I have a query related to RTK. I find myself repeating code in my action creators created with createAsyncThunk because I want to be able to cancel any request made. I am thinking of creating a wrapper to streamline this process, but I am facing challenge ...

Potential keys + keys that are present in the `initialData`

Is there a way to specify the type of data in order to include all keys that exist in initialData plus additional keys from Item as Partial(optional)? class TrackedInstance<Item extends Record<string, any>, InitialData extends Partial<Item> ...

Why does the error "property undefined" keep popping up even though I've already declared it?

Currently, I am facing an issue with toggling the theme in my project. I am encountering difficulties with the types involved, and I am unsure whether the problem lies within my TypeScript configuration or my actual code itself. I attempted to replicate t ...

Exploring the process of extending Shoelace web components with Typescript using Lit

Once I extended the <sl-button> component in Lit, I realized that TypeScript was not catching errors for incorrect attributes being passed. For instance, in the code snippet provided below, when I use <sl-button> with an incorrect attribute, ...

Having difficulty deciphering the legend in the Highcharts library for Angular (angular-highcharts)

I have a requirement to display two datasets as dual column charts. (2) [{…}, {…}] 0: historyDate: "2021-02-10T10:00:000Z" documentStatusHistory: CANCELLED: 6 COMPLETED: 52 IN_PROGRESS: 1 OPEN: 1 ...

Getting a list of the stack resources available in cloudformation using TypeScript

My team is developing an application that will deploy multiple stacks to AWS. One of these stacks is called SuperStar, and it can only exist once per AWS account. I am currently exploring how our TypeScript CDK can retrieve a list of stacks from CloudFor ...

Tips for extracting key values from an array of objects in Typescript

I am working with an array called studyTypes: const studyTypes = [ { value: "ENG", label: "ENG-RU", }, { value: "RU", label: "RU-ENG", }, ]; Additionally, I have a state variable set ...

A Guide to Filtering MongoDB Data Using Array Values

I am trying to extract specific data from a document in my collection that contains values stored in an array. { "name": "ABC", "details": [ {"color": "red", "price": 20000}, {" ...

Exploring the TypeScript Type System: Challenges with Arrays Generated and Constant Assertions

I am currently grappling with a core comprehension issue regarding TypeScript, which is highlighted in the code snippet below. I am seeking clarification on why a generated array does not function as expected and if there is a potential solution to this pr ...

How can I add multiple filters to a Kendo Grid?

Is there a way to include two separate filter fields for date filtering in Kendo Grid UI? Currently, the method I am using only allows for one date filter to be displayed. filterable: { ui: function (element: any) { element.ken ...

How to easily upload zip files in Angular 8

Currently, I am working on integrating zip file upload feature into my Angular 8 application. There are 3 specific requirements that need to be met: 1. Only allow uploading of zip files; display an error message for other file types 2. Restrict the file s ...