# 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 (opens new window) 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 Email 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/schema";

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

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 one of these decorators:

Loading in progress...

Our model is now described, we can use it inside a Controller 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} from "@tsed/platform-params";
import {Post} from "@tsed/schema";
import {Controller} from "@tsed/di";
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
21

# Primitives

Just use at least Property decorator any other schema decorator (like Email ), 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

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

      # Any types

      The Any , decorator is used to set one or more types on property. Use this method when you want to set explicitly the json type or when you use a mixed TypeScript types.

        You can also use Any decorator to allow all types:

          Since v7.75.0, when you use Any decorator combined with other decorators like MinLength , Minimum , etc. metadata will be automatically assigned to the right type. For example, if you add a Minimum decorator, it will be assigned to the number type.

          import {Any} from "@tsed/schema";
          
          class Model {
            @Any(String, Number)
            @Minimum(0)
            @MaxLength(100)
            prop: string | number;
          }
          
          1
          2
          3
          4
          5
          6
          7
          8

          Produce a json-schema as follows:

          {
            "properties": {
              "prop": {
                "allOf": [
                  {
                    "type": "string",
                    "maxLength": 100
                  },
                  {
                    "type": "number",
                    "minimum": 0
                  }
                ]
              }
            },
            "type": "object"
          }
          
          1
          2
          3
          4
          5
          6
          7
          8
          9
          10
          11
          12
          13
          14
          15
          16
          17

          # Nullable

          The Nullable decorator is used allow a null value on a field while preserving the original Typescript type.

            WARNING

            Since the v7.43.0, ajv.returnsCoercedValues is available to solve the following issue: #2355 (opens new window) If returnsCoercedValues is true, AjvService will return the coerced value instead of the original value. In this case, @Nullable() will be mandatory to allow the coercion of the value to null.

            For example if returnsCoercedValues is false (default behavior), Ts.ED will allow null value on a field without @Nullable() decorator:

            class NullableModel {
              @Property()
              propString: string; // null => null
            
              @Property()
              propNumber: number; // null => null
            
              @Property()
              propBool: boolean; // null => null
            }
            
            1
            2
            3
            4
            5
            6
            7
            8
            9
            10

            Ajv won't emit validation error if the value is null due to his coercion behavior. AjvService will return the original value and not the Ajv coerced value. Another problem is, the typings of the model doesn't reflect the real coerced value.

            Using the returnsCoercedValues option, AjvService will return the coerced type. In this case, our previous model will have the following behavior:

            class NullableModel {
              @Property()
              propString: string; // null => ''
            
              @Property()
              propNumber: number; // null => 0
            
              @Property()
              propBool: boolean; // null => false
            }
            
            1
            2
            3
            4
            5
            6
            7
            8
            9
            10

            Now @Nullable usage is mandatory to allow null value on properties:

            class NullableModel {
              @Nullable(String)
              propString: string | null; // null => null
            
              @Nullable(Number)
              propNumber: number | null; // null => null
            
              @Nullable(Boolean)
              propBool: boolean | null; // null => null
            }
            
            1
            2
            3
            4
            5
            6
            7
            8
            9
            10

            WARNING

            returnsCoercedValue will become true by default in the next major version of Ts.ED.

            # Nullable and mixed types 7.75.0+

            The Nullable decorator can be used with Tuple types:

            import {Nullable} from "@tsed/schema";
            
            class Model {
              @Nullable(String, Number)
              prop: string | number | null;
            }
            
            1
            2
            3
            4
            5
            6

            Since v7.75.0, when you use Nullable decorator combined with other decorators like MinLength , Minimum , etc. metadata will be automatically assigned to the right type. For example, if you add a Minimum decorator, it will be assigned to the number type.

            import {Nullable} from "@tsed/schema";
            
            class Model {
              @Nullable(String, Number)
              @Minimum(0)
              @MaxLength(100)
              prop: string | number | null;
            }
            
            1
            2
            3
            4
            5
            6
            7
            8

            Produce a json-schema as follows:

            {
              "properties": {
                "prop": {
                  "anyOf": [
                    {
                      "type": "null"
                    },
                    {
                      "type": "string",
                      "maxLength": 100
                    },
                    {
                      "type": "number",
                      "minimum": 0
                    }
                  ]
                }
              },
              "type": "object"
            }
            
            1
            2
            3
            4
            5
            6
            7
            8
            9
            10
            11
            12
            13
            14
            15
            16
            17
            18
            19
            20

            # Regular expressions

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

              # Format

              The Format decorator allows 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 (opens new window) can do.

                The following formats are supported for string validation with format keyword by AJV (opens new window):

                • date: full-date according to RFC3339 (opens new window).
                • 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 (opens new window).
                • 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 (opens new window) for more details:

                # MultipleOf

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

                  # Ranges

                  Ranges of numbers are specified using a combination of the Minimum and Maximum decorators, (or ExclusiveMinimum and ExclusiveMaximum for expressing exclusive range). See json-schema documentation (opens new window) for more details.

                    # Enumerated values

                    The Enum 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.

                      Enum decorator can be also in combination with BodyParams or @QueryParams@@:

                      import {Enum} from "@tsed/schema";
                      import {QueryParams, Controller} from "@tsed/common";
                      
                      @Controller("/")
                      class MyController {
                        @Post("/")
                        async method(@QueryParams("type") @Enum(MyEnum) type: MyEnum): Promise<any> {
                          return null;
                        }
                      }
                      
                      1
                      2
                      3
                      4
                      5
                      6
                      7
                      8
                      9
                      10

                      # Set label to an enum 7.17.0+

                      With OpenSpec 3 it's now possible to create shared enum for many models in components.schemas instead of having its inlined values in each model.

                      Ts.ED introduce a new function enums() to declare the enum schema as follows:

                      import {enums} from "@tsed/schema";
                      
                      enum ProductTypes {
                        ALL = "ALL",
                        ASSETS = "ASSETS",
                        FOOD = "FOOD"
                      }
                      
                      enums(ProductTypes).label("ProductTypes");
                      
                      // in models
                      class Product {
                        @Property()
                        title: string;
                      
                        @Enum(ProductTypes)
                        type: ProductTypes;
                      }
                      
                      // in controller
                      
                      import {Enum} from "@tsed/schema";
                      import {QueryParams, Controller} from "@tsed/common";
                      
                      @Controller("/products")
                      class ProductsController {
                        @Get("/:type")
                        @Returns(200, Array).Of(Product)
                        async get(@PathParams("type") @Enum(ProductTypes) type: ProductTypes): Promise<Product> {
                          return [new Product()];
                        }
                      }
                      
                      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

                      # Constant values

                      The Const decorator is used to restrict a value to a single value. For example, 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 CollectionOf (before v5.62.0, use PropertyType ) decorator as following:

                          Ts.ED provides others related collection decorators:

                          Loading in progress...

                          # Required properties

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

                          import {Required} from "@tsed/schema";
                          
                          class MyModel {
                            id: string;
                          
                            @Required()
                            prop1: string;
                          }
                          
                          1
                          2
                          3
                          4
                          5
                          6
                          7
                          8

                          You can also add a custom ajv error message with the .Error(msg) function:

                          import {Required} from "@tsed/schema";
                          
                          class MyModel {
                            id: string;
                          
                            @Required().Error("custom message")
                            prop1: string;
                          }
                          
                          1
                          2
                          3
                          4
                          5
                          6
                          7
                          8

                          # Custom AJV error messages

                          If you don't like AJV's default error messages, you can customize them with these decorators:

                          # DefaultMsg

                          This is a class decorator DefaultMsg that is used to define a default message as the name suggests:

                          import {DefaultMsg} from "@tsed/schema";
                          
                          @DefaultMsg("an error occured")
                          class MyModel {
                            id: string;
                          
                            prop1: string;
                          }
                          
                          1
                          2
                          3
                          4
                          5
                          6
                          7
                          8

                          # TypeError

                          This is a property decorator TypeError that is used to define a custom error message for a specific type:

                          import {TypeError} from "@tsed/schema";
                          
                          class MyModel {
                            id: string;
                          
                            @TypeError("prop1 should be a string")
                            prop1: string;
                          }
                          
                          1
                          2
                          3
                          4
                          5
                          6
                          7
                          8

                          # ErrorMsg

                          If none of the above work for you, you can use the ErrorMsg decorator to define your own custom error message schema using the ajv-errors documentation (opens new window):

                          import {ErrorMsg} from "@tsed/schema";
                          
                          class MyModel {
                            id: string;
                          
                            @ErrorMsg({type: "prop1 should be a string"})
                            prop1: string;
                          }
                          
                          1
                          2
                          3
                          4
                          5
                          6
                          7
                          8

                          # 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 (opens new window)).

                          Use AdditionalProperties on your model to allow this behavior:

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

                              Or by using getJsonSchema in combination with AdditionalProperty as following:

                                # Circular ref

                                Circular reference can be resolved by using arrow with a Property and CollectionOf decorators:

                                import {CollectionOf, Groups, Property} from "@tsed/schema";
                                
                                export class Photo {
                                  @Property(() => User)
                                  owner: User;
                                }
                                
                                export class User {
                                  @CollectionOf(Photo)
                                  @Groups("group.roles")
                                  photos: Photo[];
                                }
                                
                                1
                                2
                                3
                                4
                                5
                                6
                                7
                                8
                                9
                                10
                                11
                                12

                                # Custom Keys

                                Ts.ED introduces the Keyword decorator to declare a new custom validator for Ajv. Combined with the CustomKey decorator to add keywords to a property of your class, you can use more complex scenarios than what basic JsonSchema allows.

                                For example, we can create a custom validator to support the range validation over a number. To do that, we have to define the custom validator by using Keyword decorator:

                                import {Keyword, KeywordMethods} from "@tsed/ajv";
                                import {array, number} from "@tsed/schema";
                                
                                @Keyword({
                                  keyword: "range",
                                  type: "number",
                                  schemaType: "array",
                                  implements: ["exclusiveRange"],
                                  metaSchema: array().items([number(), number()]).minItems(2).additionalItems(false)
                                })
                                class RangeKeyword implements KeywordMethods {
                                  compile([min, max]: number[], parentSchema: any) {
                                    return parentSchema.exclusiveRange === true ? (data: any) => data > min && data < max : (data: any) => data >= min && data <= max;
                                  }
                                }
                                
                                1
                                2
                                3
                                4
                                5
                                6
                                7
                                8
                                9
                                10
                                11
                                12
                                13
                                14
                                15

                                Then we can declare a model using the standard decorators from @tsed/schema:

                                  Finally, we can create a unit test to verify if our example works properly:

                                  import "@tsed/ajv";
                                  import {PlatformTest} from "@tsed/common";
                                  import {getJsonSchema} from "@tsed/schema";
                                  import {Product} from "./Product";
                                  import "../keywords/RangeKeyword";
                                  
                                  describe("Product", () => {
                                    beforeEach(PlatformTest.create);
                                    afterEach(PlatformTest.reset);
                                  
                                    it("should call custom keyword validation (compile)", () => {
                                      const ajv = PlatformTest.get<Ajv>(Ajv);
                                      const schema = getJsonSchema(Product, {customKeys: true});
                                      const validate = ajv.compile(schema);
                                  
                                      expect(schema).to.deep.equal({
                                        properties: {
                                          price: {
                                            exclusiveRange: true,
                                            range: [10, 100],
                                            type: "number"
                                          }
                                        },
                                        type: "object"
                                      });
                                  
                                      expect(validate({price: 10.01})).toEqual(true);
                                      expect(validate({price: 99.99})).toEqual(true);
                                      expect(validate({price: 10})).toEqual(false);
                                      expect(validate({price: 100})).toEqual(false);
                                    });
                                  });
                                  
                                  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

                                  # Ignore

                                  deprecated

                                  The Ignore decorator is used to ignore a property in the JsonSchema generation and when you use the json-mapper.

                                  But this decorator is deprecated and will be removed in the next major version of Ts.ED. Instead, use Groups decorator to manage your model serialization/deserialization.

                                  Note

                                  To retrieve the original Ignore decorator behavior, you can use the Groups decorator. You have to set jsonMapper.strictGroups to true also:

                                  @Configuration({
                                    jsonMapper: {
                                      strictGroups: true
                                    }
                                  })
                                  
                                  1
                                  2
                                  3
                                  4
                                  5

                                  # Groups

                                  Groups decorator allows you to manage your serialized/deserialized fields by using group label. For example, with a CRUD controller, you can have many methods like POST, PUT, GET or PATCH to manage creation, update and read usecases for the exposed resource.

                                  For the creation, you don't need to have the id field but for the update, you need to have it. With the previous version for Ts.ED, you had to create the model twice, one for the creation (without id) and another one for update and read (with id). Managing many models can be a pain point for the developer, this is why the Groups decorator exists.

                                  For example, we have a User model with the following properties:

                                  import {CollectionOf, Groups, Required} from "@tsed/schema";
                                  
                                  export class User {
                                    @Groups("!creation")
                                    id: string;
                                  
                                    @Required()
                                    firstName: string;
                                  
                                    @Required()
                                    lastName: string;
                                  
                                    @Required()
                                    @Groups("group.email", "creation")
                                    email: string;
                                  
                                    @Groups("creation")
                                    password: string;
                                  
                                    @CollectionOf(String)
                                    @Groups("group.roles")
                                    roles: string[];
                                  }
                                  
                                  1
                                  2
                                  3
                                  4
                                  5
                                  6
                                  7
                                  8
                                  9
                                  10
                                  11
                                  12
                                  13
                                  14
                                  15
                                  16
                                  17
                                  18
                                  19
                                  20
                                  21
                                  22
                                  23

                                  Explanation:

                                  • !creation: This annotation indicates that the field will never be exposed when using the creation group.
                                  • group.email: This annotation indicates that the field will be exposed only if the group match with group.email or with a glob pattern like group.*.

                                  So by using the deserialize function with the extra groups options, we can map data to the expected user instance:

                                    Note

                                    The same principle works with the serialize and getJsonSchema functions!

                                    Now let's see how groups work with controllers.

                                      We can see that the Groups decorator can be used on parameter level as well as on the method through the Returns decorator. The generated OpenSpec will create automatically the appropriate JsonSchema according to the groups configuration!

                                      TIP

                                      You can combine different group labels or use a glob pattern to match multiple group labels. It's also possible to use negation by prefixing the group label with !.

                                      # Groups strict mode 7.69.0+

                                      The Groups decorator has introduced a big change in the way it manages its models, but it can sometimes be complicated to understand its default behavior when the endpoint does not define Groups.

                                      In addition, the documentation generated does not reflect the behavior observed in runtime, which adds confusion.

                                      For example, we have our User model with the following properties and Groups configuration:

                                      export class User {
                                        @Groups("!creation")
                                        id: string;
                                      
                                        @Required()
                                        firstName: string;
                                      
                                        @Required()
                                        lastName: string;
                                      
                                        @Required()
                                        @Groups("group.email", "creation")
                                        email: string;
                                      
                                        @Groups("creation")
                                        password: string;
                                      }
                                      
                                      1
                                      2
                                      3
                                      4
                                      5
                                      6
                                      7
                                      8
                                      9
                                      10
                                      11
                                      12
                                      13
                                      14
                                      15
                                      16
                                      17

                                      Now, we have this controller:

                                      class TestController {
                                        @Post("/")
                                        @Returns(200, User)
                                        async post(@BodyParams() user: User) {
                                          return user;
                                        }
                                      }
                                      
                                      1
                                      2
                                      3
                                      4
                                      5
                                      6
                                      7

                                      We can see that the Returns and the input params doesn't set any group configuration. In this case, Ts.ED will not apply any group configuration to the input params and the output.

                                      So if you send this payload:

                                      {
                                        "id": "id",
                                        "firstName": "firstName",
                                        "lastName": "lastName",
                                        "email": "",
                                        "password": "password"
                                      }
                                      
                                      1
                                      2
                                      3
                                      4
                                      5
                                      6
                                      7

                                      The endpoint will return the same payload without any modification. But here, we expect that the email and password fields are not returned because they are Groups configuration on these fields.

                                      To avoid this behavior, you can set the strictGroups option to the json-mapper:

                                      @Configuration({
                                        jsonMapper: {
                                          strictGroups: true
                                        }
                                      })
                                      
                                      1
                                      2
                                      3
                                      4
                                      5

                                      Now, if you send the same payload, the endpoint will return the following payload:

                                      {
                                        "id": "id",
                                        "firstName": "firstName",
                                        "lastName": "lastName"
                                      }
                                      
                                      1
                                      2
                                      3
                                      4
                                      5

                                      WARNING

                                      The strictGroups option is enabled by default in the next major version of Ts.ED.

                                      # Groups Name

                                      By default, Groups decorator generate automatically a name for each model impacted by the given groups list. If you use a typed client http generator based on Swagger (OAS3) to generate the client code, this behavior can be a constraint for your consumer when you change the group list.

                                      import {BodyParams, PathParams} from "@tsed/platform-params";
                                      import {Get, Groups, Post, Returns} from "@tsed/schema";
                                      import {Controller} from "@tsed/di";
                                      import {User} from "../models/User";
                                      
                                      @Controller("/")
                                      export class UsersCtrl {
                                        @Get("/:id")
                                        @Returns(200, User).Groups("group.*")
                                        async get(@PathParams("id") id: string) {}
                                      
                                        @Post("/")
                                        @Returns(201, User).Groups("group.*")
                                        async post(@BodyParams() @Groups("creation", "summary") user: User) {}
                                      }
                                      
                                      1
                                      2
                                      3
                                      4
                                      5
                                      6
                                      7
                                      8
                                      9
                                      10
                                      11
                                      12
                                      13
                                      14
                                      15

                                      In this example, the Groups annotation @Groups("creation", "summary") user: User will generate a new model name UserCreationSummary. If you change the groups list by this one:

                                       @Groups("creation", "summary", "extra") user: User
                                      
                                      1

                                      The new model name will be UserCreationSummaryExtra. This change will break the entire consumer code by removing the UserCreationSummary type and giving a new UserCreationSummaryExtra type. In fact, UserCreationSummary and UserCreationSummaryExtra are the same model with more fields!

                                      In order to minimize the impact of this kind of change Ts.ED allows to configure the postfix added to each model impacted by the groups.

                                      Here is an example with a configured GroupsName:

                                      import {BodyParams, PathParams} from "@tsed/platform-params";
                                      import {Get, Groups, Post, Returns} from "@tsed/schema";
                                      import {Controller} from "@tsed/di";
                                      import {User} from "../models/User";
                                      
                                      @Controller("/")
                                      export class UsersCtrl {
                                        @Get("/:id")
                                        @Returns(200, User).Groups("Details", ["group.*"])
                                        async get(@PathParams("id") id: string) {}
                                      
                                        @Post("/")
                                        @Returns(201, User).Groups("Details", ["group.*"])
                                        async post(@BodyParams() @Groups("Creation", ["creation", "summary"]) user: User) {}
                                      }
                                      
                                      1
                                      2
                                      3
                                      4
                                      5
                                      6
                                      7
                                      8
                                      9
                                      10
                                      11
                                      12
                                      13
                                      14
                                      15

                                      Now, @Groups("Creation", ["creation", "summary"]) user: User will generate a UserCreation type and @Returns(200, User).Groups("Details", ["group.*"]) will generate a UserDetails type.

                                      # Groups class definition

                                      It's also possible to define all groups on class instead of declaring it on each property.

                                        # ForwardGroups

                                        Groups configuration isn't forwarded to the nested models to avoid side effect on model generation. With ForwardGroups decorator, you are able to tell if a property should use or not the Groups configuration to generate correctly a nested model.

                                        class ChildModel {
                                          @Groups("!creation")
                                          id: string;
                                        
                                          @Required()
                                          prop1: string;
                                        }
                                        
                                        class MyModel {
                                          @Groups("!creation")
                                          id: string;
                                        
                                          @Groups("group.summary")
                                          @Required()
                                          prop1: string;
                                        
                                          @Groups("group.extended")
                                          @Required()
                                          prop2: string;
                                        
                                          @Property()
                                          @Required()
                                          prop3: string;
                                        
                                          @CollectionOf(ChildModel)
                                          @ForwardGroups()
                                          prop4: ChildModel[];
                                        }
                                        
                                        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

                                        Now prop4 will have a ChildModel generated along to groups configuration.

                                        # RequiredGroups

                                        As Groups decorator, RequiredGroups allow you to define when a field is required depending on the given groups strategy.

                                        The usage is the same as Groups:

                                        import {RequiredGroups, Groups, Required} from "@tsed/schema";
                                        
                                        class MyModel {
                                          @Groups("!creation")
                                          id: string;
                                        
                                          @Required()
                                          prop1: string;
                                        
                                          @RequiredGroups("!patch")
                                          @Required()
                                          prop2: string;
                                        
                                          @RequiredGroups("patch")
                                          @Required()
                                          prop3: string;
                                        }
                                        
                                        1
                                        2
                                        3
                                        4
                                        5
                                        6
                                        7
                                        8
                                        9
                                        10
                                        11
                                        12
                                        13
                                        14
                                        15
                                        16
                                        17

                                        # AllowedGroups

                                        This feature let your API consumer to define which field he wants to consume. The server will filter automatically fields based on the Groups strategy.

                                        class MyModel {
                                          @Property()
                                          id: string;
                                        
                                          @Property()
                                          description: string;
                                        
                                          @Groups("summary")
                                          prop1: string; // not display by default
                                        
                                          @Groups("details")
                                          prop2: string; // not display by default
                                        
                                          @Groups("admin")
                                          sensitiveProp: string; // not displayed because it's a sensitive props
                                        }
                                        
                                        @Controller("/controllers")
                                        class MyController {
                                          @Get("/:id")
                                          @Returns(200, MyModel).Groups("!admin").AllowedGroups("summary", "details")
                                          get() {
                                            return {
                                              id: "id",
                                              description: "description",
                                              prop1: "prop1",
                                              prop2: "prop2",
                                              sensitiveProp: "sensitiveProp"
                                            };
                                          }
                                        }
                                        
                                        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

                                        The AllowedGroups is enabled while includes query params is given in the request. Here the different scenario with this parameter:

                                          # Partial

                                          Partial allow you to create a Partial model on an endpoint:

                                          import {Returns, Patch, Partial} from "@tsed/schema";
                                          import {Controller} from "@tsed/common";
                                          import {BodyParams} from "./bodyParams";
                                          
                                          @Controller("/")
                                          class MyController {
                                            @Patch("/")
                                            @Returns(200, MyModel).Groups("group.*")
                                            async patch(@BodyParams() @Partial() payload: MyModel) {
                                              // ...
                                            }
                                          }
                                          
                                          1
                                          2
                                          3
                                          4
                                          5
                                          6
                                          7
                                          8
                                          9
                                          10
                                          11
                                          12

                                          # Advanced validation

                                          # BeforeDeserialize

                                          If you want to validate or manipulate data before the model has been deserialized you can use the BeforeDeserialize decorator.

                                          Note

                                          Don't forget to return the data in your callback function otherwise an error will occur.

                                          import {Enum, Property} from "@tsed/schema";
                                          import {BeforeDeserialize} from "@tsed/json-mapper";
                                          import {BadRequest} from "@tsed/exceptions";
                                          
                                          enum AnimalType {
                                            DOG = "DOG",
                                            CAT = "CAT"
                                          }
                                          
                                          @BeforeDeserialize((data: Record<string, unknown>) => {
                                            if (data.type !== AnimalType.DOG) {
                                              throw new BadRequest("Sorry, we're only responsible for dogs");
                                            } else {
                                              data.name = `Our dog ${data.name}`;
                                              return data;
                                            }
                                          })
                                          export class Animal {
                                            @Property()
                                            name: string;
                                            @Enum(AnimalType)
                                            type: AnimalType;
                                          }
                                          
                                          1
                                          2
                                          3
                                          4
                                          5
                                          6
                                          7
                                          8
                                          9
                                          10
                                          11
                                          12
                                          13
                                          14
                                          15
                                          16
                                          17
                                          18
                                          19
                                          20
                                          21
                                          22
                                          23

                                          # AfterDeserialize

                                          If you want to validate or manipulate data after the model has been deserialized you can use the AfterDeserialize decorator.

                                          Note

                                          Don't forget to return the data in your callback function otherwise an error will occur.

                                          import {Enum, Property} from "@tsed/schema";
                                          import {AfterDeserialize} from "@tsed/json-mapper";
                                          import {BadRequest} from "@tsed/exceptions";
                                          
                                          enum AnimalType {
                                            DOG = "DOG",
                                            CAT = "CAT"
                                          }
                                          
                                          @AfterDeserialize((data: Animal) => {
                                            if (data.type !== AnimalType.CAT) {
                                              throw new BadRequest("Sorry, we're only responsible for cats");
                                            } else {
                                              data.name = `Our cat ${data.name}`;
                                              return data;
                                            }
                                          })
                                          export class Animal {
                                            @Property()
                                            name: string;
                                            @Enum(AnimalType)
                                            type: AnimalType;
                                          }
                                          
                                          1
                                          2
                                          3
                                          4
                                          5
                                          6
                                          7
                                          8
                                          9
                                          10
                                          11
                                          12
                                          13
                                          14
                                          15
                                          16
                                          17
                                          18
                                          19
                                          20
                                          21
                                          22
                                          23

                                          # Custom validation decorator

                                          Validation can quickly become complex and therefore confusing. In this case you can use your own validation decorator.

                                          import {BeforeDeserialize} from "@tsed/json-mapper";
                                          import {Property, JsonEntityFn} from "@tsed/schema";
                                          import {BadRequest} from "@tsed/exceptions";
                                          
                                          class Company {
                                            @Property()
                                            name: string;
                                            @Property()
                                            @RequiredIf((value: any, data: any) => data.name === "tsed" && value !== undefined)
                                            location: string;
                                          }
                                          
                                          function RequiredIf(cb: any): PropertyDecorator {
                                            return JsonEntityFn((store, [target, propertyKey]) => {
                                              BeforeDeserialize((data) => {
                                                if (!cb(data[propertyKey], data)) {
                                                  throw new BadRequest(`${String(propertyKey)} is required`);
                                                }
                                                return data;
                                              })(target);
                                            });
                                          }
                                          
                                          1
                                          2
                                          3
                                          4
                                          5
                                          6
                                          7
                                          8
                                          9
                                          10
                                          11
                                          12
                                          13
                                          14
                                          15
                                          16
                                          17
                                          18
                                          19
                                          20
                                          21
                                          22

                                          # Discriminator v7.8.0+

                                          The discriminator feature allows polymorphism with JsonSchema and OpenAPI. Although OneOf already allows polymorphism in terms of validation, the latter doesn't allow the @tsed/json-mapper to render the correct class type during the deserialization (plain object to class).

                                          By declaring a discriminatorKey, @tsed/json-mapper will be able to determine the correct class which should be used.

                                          Here is an example:

                                          import {Discriminator, DiscriminatorKey, DiscriminatorValue, Property, Required, OneOf} from "@tsed/schema";
                                          
                                          export class Event {
                                            @DiscriminatorKey() // declare this property as discriminator key
                                            type: string;
                                          
                                            @Property()
                                            value: string;
                                          }
                                          
                                          @DiscriminatorValue("page_view")
                                          // or @DiscriminatorValue() value can be inferred by the class name (ex: "page_view")
                                          export class PageView extends Event {
                                            @Required()
                                            url: string;
                                          }
                                          
                                          @DiscriminatorValue("action", "click_action")
                                          export class Action extends Event {
                                            @Required()
                                            event: string;
                                          }
                                          
                                          export class Tracking {
                                            @OneOf(Action, PageView)
                                            data: Action | PageView;
                                          }
                                          
                                          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

                                          And now we can use deserialize to map plain object to a class:

                                          import {deserialize} from "@tsed/json-mapper";
                                          import {Tracking} from "./Tracking";
                                          
                                          const list = {
                                            data: [
                                              {
                                                type: "page_view",
                                                value: "value",
                                                url: "https://url"
                                              },
                                              {
                                                type: "action",
                                                value: "value",
                                                event: "event"
                                              },
                                              {
                                                type: "click_action",
                                                value: "value",
                                                event: "event"
                                              }
                                            ]
                                          };
                                          
                                          const result = deserialize(list, {
                                            type: Tracking
                                          });
                                          
                                          expect(result.data[0]).toBeInstanceOf(PageView);
                                          expect(result.data[1]).toBeInstanceOf(Action);
                                          expect(result.data[2]).toBeInstanceOf(Action);
                                          expect(result.data[3]).toBeInstanceOf(CustomAction);
                                          
                                          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

                                          Shortcut

                                          Declaring each time the list of children class using OneOf decorator can be a pain point, so Ts.ED provide a way to simplify your code:

                                          Instead of declaring all classes:

                                          export class Tracking {
                                            @OneOf(Action, PageView)
                                            data: Action | PageView;
                                          }
                                          
                                          1
                                          2
                                          3
                                          4

                                          Give the parent class to OneOf decorator:

                                          export type EventsType = Action | PageView;
                                          
                                          export class Tracking {
                                            @OneOf(Event)
                                            data: EventsType;
                                          }
                                          
                                          1
                                          2
                                          3
                                          4
                                          5
                                          6

                                          Ts.ED will automatically infer the children classes!

                                          Discriminator model can be used also on controller:

                                          @Controller("/")
                                          class Test {
                                            @Put("/:id")
                                            @Returns(200).OneOf(Event)
                                            put(@PathParams(":id") id: string, @BodyParams() @OneOf(Event) event: EventsType) {
                                              return [];
                                            }
                                          }
                                          
                                          1
                                          2
                                          3
                                          4
                                          5
                                          6
                                          7
                                          8

                                          # Generics

                                          # Declaring a generic model

                                          Sometimes, it might be useful to use generic models. TypeScript doesn't store the generic type in the metadata. This is why we need to declare explicitly the generic models with the decorators.

                                          One of the generic's usage can be a paginated list. With Returns decorator, it's now possible to declare generic type and generate the appropriate OpenSpec documentation.

                                          Starting with the pagination model, by using Generics and CollectionOf :

                                          import {CollectionOf, Generics, Property} from "@tsed/schema";
                                          
                                          @Generics("T")
                                          class Pagination<T> {
                                            @CollectionOf("T")
                                            data: T[];
                                          
                                            @Property()
                                            totalCount: number;
                                          }
                                          
                                          1
                                          2
                                          3
                                          4
                                          5
                                          6
                                          7
                                          8
                                          9
                                          10

                                          Now, we need a model to be used with the generic Pagination model:

                                          import {Property} from "@tsed/schema";
                                          
                                          class Product {
                                            @Property()
                                            id: string;
                                          
                                            @Property()
                                            title: string;
                                          }
                                          
                                          1
                                          2
                                          3
                                          4
                                          5
                                          6
                                          7
                                          8
                                          9

                                          Finally, we can use our models on a method as following:

                                            # Declaring nested generic models

                                            It's also possible to declare nested generic models in order to have this type Pagination<Submission<Product>>:

                                              # Generics with Types

                                                # Generics with Functional API

                                                  # Pagination

                                                  The following advanced example will show you how you can combine the different Ts.ED features to describe Pagination. The used features are the following:

                                                    # Deep object on query

                                                    With OpenAPI 3, it's possible to describe and use a deepObject (opens new window) style as Query params. It means, a consumer can call your endpoint with the following url:

                                                    /users?id[role]=admin&id[firstName]=Alex
                                                    
                                                    1

                                                    Ts.ED will determine automatically the appropriate style parameter based on the given User model. Here is an example with a DeepQueryObject model:

                                                    class DeepQueryObject {
                                                      @Property()
                                                      path: string;
                                                    
                                                      @Property()
                                                      condition: string;
                                                    
                                                      @Property()
                                                      value: string;
                                                    }
                                                    
                                                    @Path("/test")
                                                    class TestDeepObjectCtrl {
                                                      @OperationPath("GET", "/")
                                                      async get(@QueryParams("s") q: DeepQueryObject) {}
                                                    }
                                                    
                                                    1
                                                    2
                                                    3
                                                    4
                                                    5
                                                    6
                                                    7
                                                    8
                                                    9
                                                    10
                                                    11
                                                    12
                                                    13
                                                    14
                                                    15
                                                    16

                                                    The url to be called will be:

                                                    /test?s[path]=title&s[condition]=eq&s[value]=tsed
                                                    
                                                    1

                                                    And the generated swagger will be:

                                                    {
                                                      "components": {
                                                        "schemas": {
                                                          "DeepQueryObject": {
                                                            "properties": {
                                                              "condition": {
                                                                "type": "string"
                                                              },
                                                              "path": {
                                                                "type": "string"
                                                              },
                                                              "value": {
                                                                "type": "string"
                                                              }
                                                            },
                                                            "type": "object"
                                                          }
                                                        }
                                                      },
                                                      "paths": {
                                                        "/test": {
                                                          "get": {
                                                            "operationId": "testDeepObjectCtrlGet",
                                                            "parameters": [
                                                              {
                                                                "in": "query",
                                                                "name": "s",
                                                                "required": false,
                                                                "style": "deepObject",
                                                                "schema": {
                                                                  "$ref": "#/components/schemas/DeepQueryObject"
                                                                }
                                                              }
                                                            ]
                                                          }
                                                        }
                                                      }
                                                    }
                                                    
                                                    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

                                                    TIP

                                                    Ts.ED support also Generics Deep object style!

                                                    class FindQuery {
                                                      @Property()
                                                      tableColumnNameA?: number;
                                                    
                                                      @Property()
                                                      tableColumnNameB?: number;
                                                    }
                                                    
                                                    @Generics("T")
                                                    class PaginationQuery<T> {
                                                      @Minimum(0)
                                                      @Default(0)
                                                      offset?: number;
                                                    
                                                      @Minimum(1)
                                                      @Maximum(1000)
                                                      @Default(50)
                                                      limit?: number;
                                                    
                                                      @Property("T")
                                                      where?: T;
                                                    }
                                                    
                                                    @Path("/test")
                                                    class TestDeepObjectCtrl {
                                                      @OperationPath("GET", "/")
                                                      async get(@QueryParams() @GenericOf(FindQuery) q: PaginationQuery<FindQuery>) {}
                                                    }
                                                    
                                                    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

                                                    WARNING

                                                    This feature is only available for OpenAPI 3.

                                                    # Annotations

                                                    JSON Schema includes a few keywords and Ts.ED provide also theses corresponding decorators like Title , Description , Default , Example 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.

                                                      # Alias

                                                      Name decorator lets you rename the exposed property in your json schema.

                                                      For example mongo db uses the _id property. In order not to give any indication to our consumer about the nature of the database, it's better to rename the property to id.

                                                      import {Description, Example, Name} from "@tsed/schema";
                                                      import {ObjectID} from "@tsed/mongoose";
                                                      
                                                      export class Model {
                                                        @Name("id")
                                                        @Description("Object ID")
                                                        @Example("5ce7ad3028890bd71749d477")
                                                        _id: string;
                                                      }
                                                      
                                                      // same example with mongoose
                                                      export class Model2 {
                                                        @ObjectID("id")
                                                        _id: string;
                                                      }
                                                      
                                                      1
                                                      2
                                                      3
                                                      4
                                                      5
                                                      6
                                                      7
                                                      8
                                                      9
                                                      10
                                                      11
                                                      12
                                                      13
                                                      14
                                                      15

                                                      # Set Schema

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

                                                      # Using JsonSchemaObject

                                                      You can declare schema by using the JsonSchemaObject interface:

                                                      import {BodyParams} from "@tsed/platform-params";
                                                      import {JsonSchemaObject, Post, Returns, Schema} from "@tsed/schema";
                                                      import {Controller} from "@tsed/di";
                                                      
                                                      const ProductSchema: JsonSchemaObject = {
                                                        type: "object",
                                                        properties: {}
                                                      };
                                                      
                                                      export class MyModel {
                                                        @Schema({
                                                          contains: {
                                                            type: "string"
                                                          }
                                                        })
                                                        prop: string;
                                                      }
                                                      
                                                      @Controller("/")
                                                      class MyController {
                                                        @Post("/")
                                                        @Returns(200).Description("description").Schema(ProductSchema)
                                                        async method(@BodyParams() @Schema(ProductSchema) product: any): Promise<null> {
                                                          return null;
                                                        }
                                                      }
                                                      
                                                      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

                                                      # Using functions

                                                      It's also possible to write a valid JsonSchema by using the functional approach (Joi like):

                                                      import {BodyParams} from "@tsed/platform-params";
                                                      import {Post} from "@tsed/schema";
                                                      import {Controller} from "@tsed/di";
                                                      import {array, number, object, Returns, Schema, string} from "@tsed/schema";
                                                      
                                                      const ProductSchema = object({
                                                        id: string().required().description("Product ID"),
                                                        title: string().required().minLength(3).example("CANON D300").description("Product title"),
                                                        price: number().minimum(0).example(100).description("Product price"),
                                                        description: string().description("Product description"),
                                                        tags: array().minItems(1).items(string().minLength(2).maxLength(10).description("Product tag")).description("Product tags")
                                                      }).label("ProductModel");
                                                      
                                                      @Controller("/")
                                                      class MyController {
                                                        @Post("/")
                                                        @Returns(200).Description("description").Schema(ProductSchema)
                                                        async method(@BodyParams() @Schema(ProductSchema) product: any): Promise<null> {
                                                          return null;
                                                        }
                                                      }
                                                      
                                                      1
                                                      2
                                                      3
                                                      4
                                                      5
                                                      6
                                                      7
                                                      8
                                                      9
                                                      10
                                                      11
                                                      12
                                                      13
                                                      14
                                                      15
                                                      16
                                                      17
                                                      18
                                                      19
                                                      20
                                                      21

                                                      Here is the list of available functions:

                                                      Loading in progress...

                                                      # RecordOf

                                                      The RecordOf decorator constructs a json schema object type which property keys are set by a given set of keys and which property values are of a given type.

                                                        # 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 getJsonSchema . Here is a small example:

                                                          # Expose a JsonSchema

                                                          You can create a controller, or an endpoint to expose a specific schema with the custom keys. This can allow your consumers to retrieve a validation template so that they can use it to validate a form.

                                                          import {Controller, Get} from "@tsed/common";
                                                          import {getJsonSchema} from "@tsed/schema";
                                                          import {Product} from "../models/Product";
                                                          
                                                          @Controller("/products")
                                                          export class ProductsCtrl {
                                                            @Get("/.schema")
                                                            get(@QueryParams("customKeys") customKeys: boolean, @QueryParams("groups") groups: string[]) {
                                                              return getJsonSchema(Product, {customKeys, groups});
                                                            }
                                                          }
                                                          
                                                          1
                                                          2
                                                          3
                                                          4
                                                          5
                                                          6
                                                          7
                                                          8
                                                          9
                                                          10
                                                          11

                                                          # Get OpenSpec

                                                          In some cases, it may be useful to retrieve the OpenSpec from a Controller to generate the Swagger OpenSpec. This is possible by using getSpec . Here is a small example:

                                                            # Decorators

                                                            Loading in progress...

                                                            Last Updated: 10/5/2024, 7:24:49 PM

                                                            Other topics