0

I have a NestJS app where I need to define entities (classes that serve as Mongoose schemas) and DTOs (classes that define the API request/response shapes).

There are times where these 2 classes are nearly identical, like when you need to create a new resource.

It would be nice if I could easily reuse whatever parts I need from the Mongoose schema, remove the schema-specific decorators and then add Swagger/DTO-specific decorators.

I think something like this might be possible with class-transformer but I’m not sure. I’m also not sure if it’s even a good idea to reuse these classes in this way (in order to avoid accidentally exposing something from your db to the outside world that you shouldn’t)

Greg Thomas
  • 397
  • 3
  • 13
  • You want to think about it in terms of composable pieces. A “ResourceCreator” could be a separate class. “Resource” can be an interface that both entity and DTO implement. It’s hard to make specific recommendations without seeing any code. – Linda Paiste Feb 24 '21 at 04:19
  • Let’s say it’s a `Customer` resource with name, DOB, gender, contact info, and shipping and billing addresses. We can say `addresses` would have a type of array of `Address` classes. If both the schema and DTO classes inherit from a base `Customer` class, but both need to add their own unique decorators to every single property, won’t I just end up re-writing out every single property in the base class anyway? In this case, I would end up writing out the entire class 3 times. – Greg Thomas Feb 24 '21 at 14:53
  • I’m suggesting composition, not inheritance. I’m not sure exactly what it would look like in this case because I’m more of a front-end person. – Linda Paiste Feb 24 '21 at 15:09

0 Answers0