what is the difference between DTO's,Interfaces,and schema in nest js

Viewed 4206

I am new to Nest js in this we have some topics like Dto,interfaces,and schema can anyone provide clear Information on these topics.

1 Answers

Dto's, interfaces, and Schema are not exclusive to Nestjs.

A Data Transfer Object is an object that is used to encapsulate data, and send it from one subsystem of an application to another. In layman's terms, it formats data in a defined manner. Example: You want data for the signup Route which is passed in Body. Then you can use DTO to filter out only the required information and striping out the rest.

//signUp.dto.ts
export class signUpDto {
    @IsNotEmpty({message: "Email cannot be empty."})
    @IsEmail() //class-validators can be ignored here.
    email: string;

    @IsNotEmpty({message: "Password cannot be Empty."})
    @MinLength(6,{message: "Password must be 6 characters."})
    @MaxLength(128,{message: "Password must be less than 128."})
    password: string;
}

Now when you validate your incoming request body it would check for these two fields in the body and also the class validator rules if defined.

Interfaces: interfaces are used for type-checking and defining the types of data that can be passed to a controller or a Nest service. From NestJs documentation :

An Interface is an abstract type that includes a certain set of fields that a type must include to implement the interface

suppose you have a human interface you can implement a Doctor, professor, and everyone Example:

interface Human {
    eyeColor: string;
    hairColor: string;
}
class Doctor implements Human{
    eyeColor: string;
    hairColor: string;
}

Also, Schema is how you define your entities, integrity constraints, relations, etc. in a database. A schema can have multiple tables and have many relations such as OneToMany, ManyToOne, ManyToMany.

Hope this clears your doubts.

Related