The NestJS documentation showcases how to add DTOs to use in Controllers to validate request objects by using class-validator package. DTOs described there are TypeScript classes. Now, while controllers deal with DTOs(TS Classes), NestJS providers (or services), on the other hand, makes use of TypeScript interfaces. These DTOs and interfaces are pretty much of the same shape.
Now, I am seeing duplication of shape definition here. And wondering if the interfaces are needed at all?
Can we not make DTOs source of truth for the shape and validations? One of the approaches we were considering (to make the DTO source of truth) was, to have an openapi generator take the DTOs as input and generate openapi definition and from there another codegen can generate a set of typescript interfaces to be consumed by NestJS itself and which can be shared with another set of consumer applications like Angular too.
Have any people come across a similar problem? What do you think of the above? Feedback appreciated.
DTOs may inherit properties from multiple interfaces and using interfaces may reduce casting data between components and modules, especially in the boundaries of a single solution. Also, rules are often applied on interfaces, so DTOs should use them.
A DTO is helpful whenever you need to group values in ad hoc structures for passing data around. From a pure design perspective, DTOs are a solution really close to perfection. DTOs help to further decouple presentation from the service layer and the domain model.
But first (if you use TypeScript), we need to determine the DTO (Data Transfer Object) schema. A DTO is an object that defines how the data will be sent over the network.
Difference between DTO & Entity: Entity is class mapped to table. Dto is class mapped to "view" layer mostly. What needed to store is entity & which needed to 'show' on web page is DTO.
I think it's important to know what DTO
is.
DTO(Data Transfer Object)
is a concept of Java(J2EE)
design.
It looks like a normal Java Bean
object, which was created for transferring data object through multiple layers (such as controller
, service
, database
) in our backend, especially in Distributed Systems
.
Without DTO
Model
We send lots of requests to query some data we want, which may be duplicated.
Application -> WebService -> Database
database
, which contains some attributes should not be exposed. BTW we should manually add some additional code to limit it, which sucks.With DTO
Model
It helps us to handle our data object.
In the guide of NestJS
, DTO
acts like a HTTP Request
body.
In my opinion, DTO
contains:
Database
.and DTO
masks:
To use with class-validator
, DTO
can also help us validate data in an elegant way.
Sometimes it looks same with object interface
.
I think DTO
matters when our database collection is huge and complex.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With