NestJS, How to add DTO that has params with default value to another DTO - nestjs

I have this DTO:
class SampleDTO {
#IsNotEmpty()
#IsString()
info: string;
#IsNotEmpty()
#IsString()
user: string;
#IsNotEmpty()
#IsString()
password: string;
#IsNotEmpty()
#IsUrl()
url: string;
#IsNumber()
Currency: number = 1;
}
and i want to add this to another DTO. like this :
export class handshakeDTO {
#ValidateNested() 
#Type(() => SampleDTO)
cashier: SampleDTO;
}
Now, the issue is that all the params transferred except the Currency which has default value of 1.
How can I let nestjs add this parameter aswell.
For example: in the controller i could add default params with this:
#UsePipes(new ValidationPipe({ transform: true }))
but i cannot use it inside another DTO object .
So, is there a way to add the defulat value params?

Related

How can i have mutiple format type for a property in ApiProperty Annotation (nestjs)

Example:
import { ApiProperty, ApiParam } from '#nestjs/swagger';
export class RegisterUserDto {
#IsEmail()
#IsNotEmpty()
#ApiProperty({ type: 'string', format: 'email' })
email: string;
#IsString()
#IsNotEmpty()
#ApiProperty()
password: string;
#IsIP()
#IsNotEmpty()
#ApiParam({ type: 'string', format: ['ipv4', 'ipv6'] })
ipAddress: string;
#IsString()
#IsNotEmpty()
#ApiProperty()
country: string;
#IsString()
#ApiProperty()
profilePic: string;
}
export class DeleteUserDto {
#IsString()
#IsNotEmpty()
#ApiProperty()
email: string;
}
export default RegisterUserDto;
here I want to define format with ipv4 and ipv6 for ipAddress
type of format in typescript definition is string
I tried looking into documentation of nestjs: https://docs.nestjs.com/openapi/introduction
but didn't find anything regarding this

How to handle empty strings with class validators in TypeORM

I want to create users from my Postman, I want to test my API endpoints, as it stands, it is possible to create a user if I pass something like " " as a value for the name column, how can I handle that in TypeORM? I don't know any class validator. My Dto file is below:
import { IsNotEmpty, IsString } from 'class-validator';
export class CreateRoomUserDto {
#IsNotEmpty()
#IsString()
public name: string;
#IsNotEmpty()
#IsString()
public room_interest: string;
#IsNotEmpty()
#IsString()
public occupation: string;
}
This is the entity file below
#import { IsNotEmpty } from 'class-validator';
import { Entity, PrimaryGeneratedColumn, Column, CreateDateColumn, UpdateDateColumn, OneToMany } from 'typeorm';
import { RoomUser } from '#/interfaces/room-user.interface';
Entity()
export class RoomUserEntity implements RoomUser {
#PrimaryGeneratedColumn()
id: string;
#Column()
#IsNotEmpty()
name: string;
#Column()
#IsNotEmpty()
room_interest: string;
#Column()
#IsNotEmpty()
occupation: string;
#CreateDateColumn()
createdAt: Date;
#Column()
#UpdateDateColumn()
updatedAt: Date;
}
The code below solves the problem, however, it is only able to catch the error if it is an empty array with just white space but it is not able to do anything if there's a white space at the beginning and/or the end of the string.
export class CreateRoomUserDto {
#IsNotEmpty()
#IsString()
#Transform(({ value }: TransformFnParams) => value?.trim())
public name: string;
#IsNotEmpty()
#IsString()
#Transform(({ value }: TransformFnParams) => value?.trim())
public room_interest: string;
#IsNotEmpty()
#IsString()
#Transform(({ value }: TransformFnParams) => value?.trim())
public occupation: string;
}

mongo object id is not generating inside object of array

I am using nestJs for the backend and I have a schema that has an array as an attribute. I need an object id for each array attribute for some purpose but ids are not generating.
DTO for object inside array:
export class EmergencyContact {
#Prop({ _id: true })
_id: string;
#Prop()
#ApiProperty()
#IsNotEmpty()
title: string;
#Prop()
#ApiProperty()
#IsNotEmpty()
contactNumber: string;
#Prop()
status: boolean;
}
Schema DTO:
#Schema({ timestamps: true })
export class EDiary {
_id: string;
#Prop()
#ApiProperty()
#IsNotEmpty()
state: string;
#ApiProperty()
#Prop()
#Type(() => EmergencyContact)
emergencyContact: EmergencyContact[];
}
After research on the internet, I found one solution to the above issue. To get the MongoDB object id inside I did the following changes to my DTO.
export class EmergencyContact {
#Prop()
_id: string;
#Prop()
#ApiProperty()
#IsNotEmpty()
title: string;
#Prop()
#ApiProperty()
#IsNotEmpty()
contactNumber: string;
#Prop()
status: boolean;
}
#Schema({ timestamps: true })
export class EDiary {
_id: string;
#Prop()
#ApiProperty()
#IsNotEmpty()
state: string;
#ApiProperty()
#ApiProperty()
#Prop([{
title: {
type: String
},
contactNumber: {
type: String
}, status: {
type: Boolean
}
}])
#Type(() => EmergencyContact)
emergencyContact: EmergencyContact[];
}

NestJS class-validator validate array of numbers in form data

How can I handle the validation of an array of numbers in form data?
Because I am passing data in a form-data format, I can't validate an array of numbers Actually, I don't know how to do it.
This is my CreatePostDto:
export class CreatePostDto {
#IsNotEmpty()
#IsString()
#MinLength(3)
title: string;
#ApiProperty({ type: 'string', format: 'binary' })
thumbnail: any;
#IsNotEmpty()
#IsString()
#MinLength(20)
#MaxLength(300)
description: string;
#IsNotEmpty()
#IsString()
#MinLength(20)
body: string;
#IsOptional()
#Type(() => Number)
#IsNumberString({}, { each: true })
tags: number[];
#IsOptional()
#Type(() => Number)
#IsNumberString({}, { each: true })
categories: number[];
#IsBooleanString()
published: boolean;
}
A decision:
https://github.com/typestack/class-validator/issues/454
Short answer:
#IsNumber({},{each: true})
numbers: number[];

class-validator doesn't validate entity

Can I use class-validator to validate Entity columns?
This doesn't validate the columns:
import { IsEmail } from 'class-validator';
#Entity()
export class Admin extends BaseEntity {
#Column({ unique: true })
#IsEmail()
email: string;
}
However when I use the class-validator anywhere else in the code other than entities it validates properly and doesn't allow for bad inputs.
This works:
#InputType()
export class RegisterInput {
#Field()
#IsEmail()
email: string;
}
The Entity should be clean
#Entity()
export class Admin extends BaseEntity {
#Column({ unique: true })
email: string;
}
While you define a DTO for checking the incoming request.
export class AdminDto {
#IsEmail()
email: string;
}
In your controller, you would check the incoming request with your AdminDto.
#Controlller('route')
export class AdminController {
constructor(private yourService: yourserviceClass)
#Post('/api')
async createSomething(#Body('email', ValidationPipe) email: string){ //Your request body //would be checked against your DTO
this.yourService.createMethod(email)
}
Hope this answers your question.

Resources