# Model

The classes can be used as a model in your application. Ts.ED uses these models to convert JSON objects to their class equivalents.

The classes models can be used in the following cases:

To create a model, Ts.ED provides decorators which will store and generate a standard JsonSchema model.

WARNING

Validation is only available when you import @tsed/ajv package in your server.

import {Configuration} from "@tsed/common";
import "@tsed/ajv";

@Configuration()
class Server {}
1
2
3
4
5

Without this package, decorators like won't have any effect.

# Example

The example below uses decorators to describe a property of the class and store metadata such as the description of the field.

import {
  Default,
  Enum,
  Format,
  Maximum,
  MaxLength,
  Minimum,
  MinLength,
  Pattern,
  Required
} from "@tsed/common";

enum Categories {
  CAT1 = "cat1",
  CAT2 = "cat2"
}

export class MyModel {
  _id: string;

  @Required()
  unique: string;

  @MinLength(3)
  @MaxLength(50)
  indexed: string;

  @Minimum(0)
  @Maximum(100)
  @Default(0)
  rate: Number = 0;

  @Enum(Categories)
    // or @Enum("type1", "type2")
  category: Categories;

  @Pattern(/[a-z]/)
  pattern: String;

  @Format("date-time")
  @Default(Date.now)
  dateCreation: Date = new Date();
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43

TIP

The Model will generate a JsonSchema which can be used by modules supporting JsonSchema spec

WARNING

The schema generated by Ts.ED lists only properties decorated by at least one decorator. In the previous example, the _id won't be displayed in the JsonSchema. It's very important to understand that TypeScript only generates metadata on properties with at least of theses decorators:

    Our model is now described, we can use it inside a as input type parameter for our methods. Ts.ED will use the model to convert the raw data to an instance of your model.

    import {BodyParams, Controller, Post} from "@tsed/common";
    import {PersonModel} from "../models/PersonModel";
    
    @Controller("/")
    export class PersonsCtrl {
    
      @Post("/")
      save(@BodyParams() model: PersonModel): PersonModel {
        console.log(model instanceof PersonModel); // true
        return model; // will be serialized according to your annotation on PersonModel class.
      }
    
      // OR
    
      @Post("/")
      save(@BodyParams("person") model: PersonModel): PersonModel {
        console.log(model instanceof PersonModel); // true
        return model; // will be serialized according to your annotation on PersonModel class.
      }
    }
    
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20

    # Primitives

    Just use at least decorator any other schema decorator (like ), to create a new property on a model. Ts.ED will get the type from Typescript metadata and transform this type to a valid Json type.

      # Integer v5.62.0+

      The decorator is used to set integer type for integral numbers.

        # Any types

        The (before v5.62.0, use ) decorator is used to set one or more types on property. Use this method when you when to set explicitly the json type or when you use a mixed TypeScript types.

          # Regular expressions

          The decorator is used to restrict a string to a particular regular expression. The regular expression syntax is the one defined in JavaScript (ECMA 262 specifically). See Regular Expressions for more information.

            # Format

            The decorator allows for basic semantic validation on certain kinds of string values that are commonly used. This allows values to be constrained beyond what the other tools in JSON Schema, including Regular Expressions can do.

              The following formats are supported for string validation with format keyword by AJV:

              • date: full-date according to RFC3339.
              • time: time with optional time-zone.
              • date-time: date-time from the same source (time-zone is mandatory).
              • uri: full uri with optional protocol.
              • email: email address.
              • hostname: host name according to RFC1034.
              • ipv4: IP address v4.
              • ipv6: IP address v6.
              • regex: tests whether a string is a valid regular expression by passing it to RegExp constructor.

              See built-in formats types on Jsonp-schema.org for more details:

              # MultipleOf

              Numbers can be restricted to a multiple of a given number, using the decorator. It may be set to any positive number. See json-schema documentation for more details.

                # Ranges

                Ranges of numbers are specified using a combination of the and decorators, (or and for expressing exclusive range). See json-schema documentation for more details.

                  # Enumerated values

                  The decorator is used to restrict a value to a fixed set of values. It must be an array with at least one element, where each element is unique or a TypeScript enum.

                    # Constant values

                    The decorator is used to restrict a value to a single value. For example, to if you only support shipping to the United States for export reasons:

                      # Collections

                      Declaring a property that uses a collection is a bit different than declaring a simple property. TypeScript stores only the Array/Set/Map type when you declare the type of your property. The type used by the collection is lost.

                      To tell Ts.ED (and other third party which uses JsonSchema) that a property uses a collection with a specific type, you must use (before v5.62.0, use ) decorator as following:

                        Ts.ED provide others related collection decorators:

                        # Required properties

                        By default, the properties defined with a decorator are not required. However, one can use decorator to add a required property to the json schema.

                        # Additional properties

                        Sometimes, it can be useful to create model with additional properties. By default, Json schema is strict over extra properties not declared in a model (see Properties json schema documentation).

                        Use on your model to allow this behavior:

                          It also possible to add contraint on additional properties, by giving a raw Json schema:

                            Or by using in combination with as following:

                              # Annotations

                              JSON Schema includes a few keywords and Ts.ED provide also theses corresponding decorators like , , , that aren’t strictly used for validation, but are used to describe parts of a schema.

                              None of these annotation keywords are required, but they are encouraged for good practice, and can make your schema self-documenting.

                                # Set raw schema

                                If Ts.ED doesn't provide the expected decorator to describe your json schema, you can use the decorator from @tsed/common to set an inline schema:

                                  # Get Json schema

                                  In some cases, it may be useful to retrieve the JSON Schema from a Model to use with another library. This is possible by using . Here a small example:

                                    # Decorators