Warm tip: This article is reproduced from serverfault.com, please click

NestJS Mapped Types and DTO usage

发布于 2021-07-23 10:00:54

I'm confused about the mapped types in NestJS.

The documentation says that PartialType create a new class making its validation decorators optional.

So, we use it in our validation pipes as we do with the original classes.

I'm wondering if it's the normal usage of the derived classes. I mean, to make it easy to create a partial update DTO.

And if so, why is it in a swagger package (or graphql) and not in a utils of the core?

Questioner
jbdemonte
Viewed
11
Jay McDoniel 2021-07-24 01:25:37

So, there's three mapped-types in Nest actually: the base @nestjs/mapped-types, the one in @nestjs/swagger, and the one in @nestjs/graphql. The reason for these packages is to allow devs to define a base class, and then be able to define classes that extend off this base class but use different decorators for validations/schema definitions. These mixin methods become useful because they read the existing metadata on the class and make modifications to it for the resulting class, like making every property optional, or leaving out key properties, like a password field on a User class.

The @nestjs/mapped-types package deals with class-validator and class-transformer metadata and is the basis for the other two packages. If the metadata doesn't exist, nothing is effected in terms of metadata, and the types are the only thing updated.

@nestjs/swagger's mapped-types update the swagger schema metadata so that your OpenAPI spec shows up properly.

Similarly, the @nestjs/graphql mapped-types updates the GraphQL schema so that Apollo doesn't throw exceptions on partial updates.

Because all of this metadata is handled differently, and it doesn't overlap, is the reason for three different ways to deal with it. Also, to help keep the base package small, rather than requiring the metadata keys from the other two packages.