NestJS 中的模型与 DTO [英] Models vs DTO in NestJS

查看:308
本文介绍了NestJS 中的模型与 DTO的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对 NestJS 完全陌生.我已经看到在 NestJS 中,创建了一个模型来指定数据的详细信息,例如在创建一个简单的任务管理器时,当我们想要指定单个任务的外观时,我们在模型中指定(示例如下):

I am completely new to NestJS. I have seen that in NestJS, a model is created to specify the details of data, e.g. when creating a simple task manager, when we want to specify what a single task will look like, we specify it in the model (example below):

export interface Task {
  id: string;
  title: string;
  description: string;
  status: TaskStatus;
}

export enum TaskStatus {
  OPEN = 'OPEN',
  IN_PROGRESS = 'IN_PROGRESS',
  DONE = 'DONE',
}

但是,我后来遇到了 DTO,其中再次描述了数据的形状.我的理解是在传输数据时使用 DTO,即它描述了您将发布或获取的数据类型.

However, I later came across DTOs, where once again the shape of data is described. My understanding is that DTOs are used when transferring data, i.e. it describes the kind of data that you will post or get.

我的问题是,当我已经使用 DTO 来描述数据的形状时,为什么还要使用模型?

My question is that when I am already using DTOs to describe the shape of data, why use Models at all?

此外,我读到使用 DTO 我们可以拥有单一的事实来源,如果我们意识到数据结构需要更改,我们不必在控制器和服务文件中单独指定它,但是,这仍然意味着我们必须更新模型吗?

Also, I read that with DTOs we can have a single source of truth and in case we realise that the structure of data needs to change, we won't have to specify it separately in the controller and service files, however, this still means we will have to update the Model?

推荐答案

在很长一段时间内的大部分时间里,您的 DTO 和您的模型可能并且将会彼此不同.来自 HTTP 请求的内容和返回的内容可以采用与数据库中保存的格式不同的格式,因此随着时间的推移,将它们分开可以带来更大的灵活性.这基本上属于 DTO(数据传输对象)DAO(数据访问对象) 与 DTAO(数据传输/访问对象)(至少我是这么称呼它们的).

Most of the time over a long period of time your DTOs and your models can and will diverge from each other. What comes of the the HTTP request and what gets sent back can be in a different format than what is kept in your database, so keeping them separate can lead to more flexibility as time goes on. This basically comes into an argument of DTO (Data Transfer Objects) and DAO (Data Access Object) versus DTAO (Data Transfer/Access Object) (at least that's what I call them).

这也涉及单一职责原则,因为每个类都应该处理一个一件事,只有一件事.

This also deals with the Single Responsibility Principle as each class should deal with one thing and one thing only.

还有一个来自 Java 线程的 SO 帖子,讨论了您的想法

这篇关于NestJS 中的模型与 DTO的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆