• Что бы вступить в ряды "Принятый кодер" Вам нужно:
    Написать 10 полезных сообщений или тем и Получить 10 симпатий.
    Для того кто не хочет терять время,может пожертвовать средства для поддержки сервеса, и вступить в ряды VIP на месяц, дополнительная информация в лс.

  • Пользаватели которые будут спамить, уходят в бан без предупреждения. Спам сообщения определяется администрацией и модератором.

  • Гость, Что бы Вы хотели увидеть на нашем Форуме? Изложить свои идеи и пожелания по улучшению форума Вы можете поделиться с нами здесь. ----> Перейдите сюда
  • Все пользователи не прошедшие проверку электронной почты будут заблокированы. Все вопросы с разблокировкой обращайтесь по адресу электронной почте : info@guardianelinks.com . Не пришло сообщение о проверке или о сбросе также сообщите нам.

Relationships between DTO(Data Transfer Object) and Entity in Nest

Lomanu4 Оффлайн

Lomanu4

Команда форума
Администратор
Регистрация
1 Мар 2015
Сообщения
1,481
Баллы
155
Dto files act as a gatekeeper for endpoint, ensuring that only correctly shaped and validated data makes it into your application's logic.

DTOs work with class-validator decorators (and class-transformer).
In a NestJS application, you typically don't call plainToInstance in your controllers. You enable the ValidationPipe globally in main.ts
With transform: true in the ValidationPipe options, NestJS internally uses class-transformer's plainToInstance to convert the raw request body into an instance of your DTO class before class-validator performs the validation.

This is why you can type your controller parameters like
public async create(@Body() createTaskDto:CreateTaskDto): Promise<Task>

It rimarily belong to the API layer (controllers) and sometimes the service layer (when passing validated data around).

It serves as:


  1. API Contract:
    They specify the expected structure of incoming request bodies (e.g., for POST or PUT requests) or the structure of outgoing responses.


  2. Validation:
    Crucially, they are used with class-validator decorators (@IsNotEmpty(), @IsString(), @IsUUID(), etc.) to automatically validate incoming data against predefined rules.

3.Decoupling: Separation of Concerns
They decouple the external API contract from your internal database schema. You might not want to expose all entity fields to the client, or you might want to combine fields from multiple entities into a single DTO for a response.

Entity: serve for Object-Relational Mapper (ORM) like TypeORM.
Purpose:


  1. Database Mapping: They dictate the columns, their types, primary keys, foreign keys, and relationships between tables.


  2. Business Logic (sometimes): While primary business logic often lives in services, entities can sometimes contain methods related to their own

import { Column, Entity, ManyToOne, PrimaryGeneratedColumn } from 'typeorm';

It primarily belong to the data access layer or ORM layer.

Client Request (JSON)
|
V
Controller (@ Body() uses DTO)
|
V
ValidationPipe (uses class-validator decorators on DTO)
| (if valid)
V
Service Layer (receives validated DTO)
|
V
(Conversion: DTO **-> **Entity)
|
V
Repository (uses Entity to interact with DB)
|
V
Database (stores data based on Entity schema)
|
V
(Conversion: Entity -> Response DTO - Optional)
|
V
Controller (sends JSON Response based on Entity/Response DTO)
|
V
Client receives Response (JSON)


Пожалуйста Авторизируйтесь или Зарегистрируйтесь для просмотра скрытого текста.




Пожалуйста Авторизируйтесь или Зарегистрируйтесь для просмотра скрытого текста.

 
Вверх Снизу