2
votes

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',
}

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.

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

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?

1

1 Answers

4
votes

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.

There's also this SO post from a Java thread that talks about what you're thinking of