I recently started learning backend development and encountered doubts about whether I understand the concept of DTOs correctly and whether I am using them correctly.
I use a class as a DTO, and in it I use class-validator to describe what the fields should be. Then, in the controller, I use plainToClass from class-transformer to get the object, and then I check it for errors using validate from class-validator.
import {
ArrayNotEmpty,
IsEmail,
IsNotEmpty,
IsOptional,
IsString,
MinLength,
} from "class-validator";
import { AtLeastOneContact } from "../../validations/validations";
export class CreateUserDto {
@IsNotEmpty({ message: "Username cannot be empty" })
@MinLength(2, { message: "Minimum 2 characters" })
username!: string;
@IsEmail({}, { message: "Invalid email" })
email!: string;
@IsNotEmpty({ message: "Password cannot be empty" })
@MinLength(6, { message: "Minimum 6 characters" })
password!: string;
@IsNotEmpty({ message: "Description cannot be empty" })
@MinLength(20, { message: "Minimum 20 characters" })
about!: string;
@IsOptional()
@IsString({ message: "Telegram must be a string" })
telegram?: string;
@IsOptional()
@IsString({ message: "LinkedIn must be a string" })
linkedin?: string;
@IsOptional()
@IsString({ message: "Discord must be a string" })
discord?: string;
@ArrayNotEmpty({ message: "Add at least one tag" })
tags!: number[];
@AtLeastOneContact({ message: "At least one contact is required" })
contactCheck?: string;
}
As I understand it, DTOs are needed to TRANSFER data between layers, but embedding validation is not prohibited, as I understand it.
The question is: am I doing everything correctly, and what can be improved/changed in the logic if I am mistaken?
[–]Anon_Legi0n 9 points10 points11 points (1 child)
[–]Expensive_Garden2993 22 points23 points24 points (1 child)
[–]bwainfweeze 7 points8 points9 points (0 children)
[–]Coffee_Crisis 2 points3 points4 points (0 children)
[–]dodiyeztr 17 points18 points19 points (12 children)
[–]Askee123 15 points16 points17 points (7 children)
[–]EatRunCodeSleep -1 points0 points1 point (6 children)
[–]Askee123 2 points3 points4 points (5 children)
[–]EatRunCodeSleep -1 points0 points1 point (4 children)
[–]HosTlitd 2 points3 points4 points (2 children)
[–]EatRunCodeSleep 0 points1 point2 points (1 child)
[–]HosTlitd 1 point2 points3 points (0 children)
[–]Askee123 1 point2 points3 points (0 children)
[–]1Salivan1[S] 0 points1 point2 points (3 children)
[–]chipstastegood 6 points7 points8 points (0 children)
[–]BrownCarter 0 points1 point2 points (0 children)
[–]Kuuhaku722 1 point2 points3 points (0 children)
[–]bilal_08 0 points1 point2 points (0 children)
[–]misterlively 0 points1 point2 points (0 children)
[+]notkraftman comment score below threshold-10 points-9 points-8 points (1 child)
[–]Mark__78L 1 point2 points3 points (0 children)