0.4.1 • Published 3 years ago

@hippo-oss/dto-decorators v0.4.1

Weekly downloads
-
License
MIT
Repository
github
Last release
3 years ago

dto-decorators

DTO type decorators and factories.

Defines types for decorating DTO classes and a mechanism for composing multiple implementations of these decorators.

What Problem Does This Project Solve?

TypeScript applications must take special care at their boundaries to ensure that runtime data matches its type definitions. For example, many applications will extract JSON from an HTTP request might and (naively) cast this data to a TypeScript type:

const input = await request.json() as MyInputType

This approach, however, offers no guarantee that the input type actually matches the type declaration; a cast merely tells tsc that a type should be treated in a particular way.

A common solution to this mismatch is to perform runtime validation of a Data Transfer Object (DTO), thereby ensuring that the declared type of each data item matches its actual type.

const json = await request.json();
const input = validate(MyInputType, json);

Because TypeScript types lose their type information at runtime, the DTO strategy only works if some other layer instruments DTOs with runtime metadata. A common solution in this space is to use decorators to attach type information to class.

This approach is so popular, in fact, that there are many implementations end up using multiple decorator libraries, including:

This library aims to provide an implementation-agnostic decorator API that can be used to generate appropriate decorators across multiple library implementations without introducing rendundant decorator information.

Decorator Flavors

This library defines a set of types that can be used to produce implementation-specific decorator "flavors", including a noop implementation (provided in this library) and several others (provided in other libraries).

  • class-decorators implements a flavor that uses class-transformer and class-validator to convert and validate DTO types.

  • metadata-decorators implements a flavor that persists decorator metadata using reflect-metadata.

  • deprecation-decorators implements a flavor that raises a system warnings when a deprecated property is set.

Decorator Composition

The real power of dto-decorators comes from composing these decorators flavors with each other -- or with implementations that use other third-party dependencies. Composition is as easy as:

import { composeDecoratorFactories } from '..';

const decorators = composeDecoratorFactories([
    MY_DECORATORS,
    SOME_OTHER_DECORATORS,
]);

const { IsInteger } = decorators;

```ts
class Example {

    @IsInteger({
        description: 'An example value',
    })
    public value!: number;
}

Available Decorators

The following decorators are supported:

DecoratorDescription
IsBooleanDeclares a boolean value.
IsDateDeclares a Date value.
IsDateStringDeclares an ISO 8601 date string.
IsEnumDeclares an enumerated value.
IsIntegerDeclares an integer number.
IsNestedDeclares a nested object type.
IsNumberDeclares a floating point number.
IsStringDeclares a string.
IsUUIDDeclares a UUID string.

Decorator Options

Decorators may be passed various options, depending on their type.

All options are optional expect where indicated.

OptionDecoratorDescription
descriptionallDescription of the field; exposed in OpenAPI.
exposeallEnables alternate name to be set for the field.
isArrayallDesignates an array of values.
nameallAlternate name of the field; exposed in OpenAPI.
nullableallWhether the field can be set to null.
optionalallWhether the field be set to undefined or omitted.
deprecatedallWhether the field appears as deprecated
----------------------------------------------------------------------------------
formatIsDateThe OpenaPI date format; defaults to date-time.
----------------------------------------------------------------------------------
formatIsDateStringThe OpenAPI date format; defaults to date.
----------------------------------------------------------------------------------
enum (required)IsEnumThe enum type.
enumNameIsEnumThe enum name; required to correctly export OpenAPI
----------------------------------------------------------------------------------
maxValueIsIntegerThe maximum value of the field.
minValueIsIntegerThe minimum value of the field.
----------------------------------------------------------------------------------
type (required)IsNestedThe nested type.
----------------------------------------------------------------------------------
maxValueIsNumberThe maximum value of the field.
minValueIsNumberThe minimum value of the field.
----------------------------------------------------------------------------------
maxLengthIsStringThe maximum length of the string.
minLengthIsStringThe minimum length of the string.
patternIsStringA regex pattern for validating the string.
----------------------------------------------------------------------------------
versionIsUUIDThe type of UUID.

Array Options

Any property can be declared as an array:

class Example {
   @IsString({
       isArray: true,
   })
   values!: string[];
}

The isArray option may be supplied as either the literal true or as ArraySizeOptions:

class Example {
   @IsString({
       isArray: {
           maxSize: 30,
           minSize: 0,
       },
   })
   values!: string[];
}

Enum Options

Enumerated types work pretty much as expected:

enum Color {
  Red = 'Red',
  Blue = 'Blue',
  Green = 'Green',
}

class Example {
   @IsEnum({
      enum: Color,
      enumName: 'Color',
   })
   color!: Color;
}

The enumName value is optional, but encouraged. Some library implementations will not be able to correctly correlate the same enum value across multiple usages without a unifying name.

Nested Options

Decorator values that use another object type should be decorated with IsNested:

class Child {
    @IsString()
    value!: string;
}

class Parent {
     @IsNested({
         type: Child,
     })
     child!: Child;
}

Every child type is expected to define at least one decorator field. Failure to do so may result in errors in some library implementations.