{"id":17100315,"url":"https://github.com/rsinger86/dto-classes","last_synced_at":"2025-07-01T18:05:59.173Z","repository":{"id":172524901,"uuid":"643079477","full_name":"rsinger86/dto-classes","owner":"rsinger86","description":"DTO classes for TypeScript projects.","archived":false,"fork":false,"pushed_at":"2023-06-11T20:06:44.000Z","size":265,"stargazers_count":78,"open_issues_count":2,"forks_count":2,"subscribers_count":2,"default_branch":"master","last_synced_at":"2025-06-28T01:48:34.558Z","etag":null,"topics":["dto","nestjs","parsing","typescript","validation"],"latest_commit_sha":null,"homepage":"","language":"TypeScript","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":null,"status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/rsinger86.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":null,"code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null}},"created_at":"2023-05-20T03:37:22.000Z","updated_at":"2025-01-06T00:47:07.000Z","dependencies_parsed_at":"2024-01-07T01:17:11.499Z","dependency_job_id":"29875e4a-e78b-4cc4-90af-212af659d5da","html_url":"https://github.com/rsinger86/dto-classes","commit_stats":null,"previous_names":["rsinger86/dto-classes"],"tags_count":2,"template":false,"template_full_name":null,"purl":"pkg:github/rsinger86/dto-classes","repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/rsinger86%2Fdto-classes","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/rsinger86%2Fdto-classes/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/rsinger86%2Fdto-classes/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/rsinger86%2Fdto-classes/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/rsinger86","download_url":"https://codeload.github.com/rsinger86/dto-classes/tar.gz/refs/heads/master","sbom_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/rsinger86%2Fdto-classes/sbom","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":263013712,"owners_count":23399813,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["dto","nestjs","parsing","typescript","validation"],"created_at":"2024-10-14T15:13:09.148Z","updated_at":"2025-07-01T18:05:59.112Z","avatar_url":"https://github.com/rsinger86.png","language":"TypeScript","funding_links":[],"categories":["Validation"],"sub_categories":["Runtime"],"readme":"# Introduction\n\nDTO Classes is a TypeScript library for modelling data transfer objects in HTTP JSON APIs.\n\nIt gives you the following, a bundle I've found missing for TypeScript/Node:\n- Class-based schemas that serialize *and* deserialize:\n  - Parse/validate JSON to internal objects\n  - Format internal objects to JSON\n- Static types by default without an additional `infer` call\n- Custom validation by adding methods to a schema class\n- Simple way to access additional context (eg the request object) when parsing\n- Async parsing \u0026 formatting to play nice with ORMs\n- An API broadly similar to OpenAPI and JSON Schema\n\nExample:\n\n```typescript\nimport { DTObject, ArrayField, BooleanField, StringField, DateTimeField } from \"dto-classes\";\n\nclass UserDto extends DTObject {\n    name = StringField.bind()\n    nickName = StringField.bind({ required: false })\n    birthday = DateTimeField.bind()\n    active = BooleanField.bind({ default: true })\n    hobbies = ArrayField.bind({ items: StringField.bind() })\n    favoriteColor = StringField.bind({ allowNull: true })\n}\n\nconst userDto = await UserDto.parse({\n    name: \"Michael Scott\",\n    birthday: '1962-08-16',\n    hobbies: [\"Comedy\", \"Paper\"],\n    favoriteColor: \"Red\"\n});\n```\n\nVS Code:\n\n![Alt Text](vs-code-demo-1.gif)\n\n# Table of Contents\n\n\u003c!-- TOC --\u003e\n\n- [Introduction](#introduction)\n- [Table of Contents](#table-of-contents)\n- [Installation](#installation)\n    - [From npm](#from-npm)\n    - [Config](#config)\n- [Basic Usage](#basic-usage)\n    - [Parsing \u0026 Validating Objects](#parsing--validating-objects)\n    - [Formatting Objects](#formatting-objects)\n- [Fields](#fields)\n    - [StringField: string](#stringfield-string)\n    - [BooleanField: boolean](#booleanfield-boolean)\n    - [NumberField: number](#numberfield-number)\n    - [DateTimeField: Date](#datetimefield-date)\n    - [ArrayField: Array\u003cT\u003e](#arrayfield-arrayt)\n    - [CombineField: oneOf, anyOf](#combinefield-oneof-anyof)\n    - [Nested Objects: DTObject](#nested-objects-dtobject)\n- [Error Handling](#error-handling)\n- [Custom Parsing/Validation](#custom-parsingvalidation)\n- [Custom Formatting](#custom-formatting)\n- [Recursive Objects](#recursive-objects)\n- [Standalone Fields](#standalone-fields)\n- [NestJS](#nestjs)\n    - [Simple Validation Pipe](#simple-validation-pipe)\n    - [Validation Pipe with Request Context](#validation-pipe-with-request-context)\n\n\u003c!-- /TOC --\u003e\n\n# Installation\n\nTypeScript 4.5+ is required. \n\n## From npm\n```npm install dto-classes```\n\n## Config\nYou'll get more accurate type hints with `strict` set to `true` in your `tsconfig.json`:\n```jsonc\n{\n  \"compilerOptions\": {\n    // ...\n    \"strict\": true\n    // ...\n}\n```\n\nIf that's not practical, you'll still get useful type hints by setting `strictNullChecks` to `true`:\n```jsonc\n{\n  \"compilerOptions\": {\n    // ...\n    \"strictNullChecks\": true\n    // ...\n}\n```\n\n# Basic Usage\n\nThe library handles both _parsing_, the process of transforming inputs to the most relevant types, and _validating_, the process of ensuring values meet the correct criteria.\n\nThis aligns with the [robustness principle](https://en.wikipedia.org/wiki/Robustness_principle). When consuming an input for an age field, most applications will want the string `\"25\"` auto-converted to the number `25`. However, you can override this default behavior with your own custom `NumberField`.\n\n## Parsing \u0026 Validating Objects\n\nLet's start by defining some schema classes. Extend the `DTObject` class and define its fields:\n\n```typescript\nimport { DTObject, StringField, DateTimeField } from 'dto-classes';\n\nclass DirectorDto extends DTObject {\n    name = StringField.bind()\n}\n\nclass MovieDto extends DTObject {\n    title = StringField.bind()\n    releaseDate = DateTimeField.bind()\n    director = DirectorDto.bind(),\n    genre = StringField.bind({required: false})\n}\n```\n\nThere's some incoming data:\n```typescript\nconst data = {\n    \"title\": \"The Departed\",\n    \"releaseDate\": '2006-10-06',\n    \"director\": {\"name\": \"Martin Scorsese\"}\n}\n```\n\nWe can coerce and validate the data by calling the static method `parse(data)` which will return a newly created DTO instance:\n\n```typescript\nconst movieDto = await MovieDto.parse(data);\n```\n\nIf it succeeds, it will return a strongly typed instance of the class. If it fails, it will raise a validation error:\n\n```typescript\nimport { ParseError } from \"dto-classes\";\n\ntry {\n    const movieDto = await MovieDto.parse(data);\n} catch (error) {\n    if (error instanceof ParseError) {\n        // \n    }\n}\n```\n\nFor incoming `PATCH` requests, the convention is to make all fields optional, even if they'd otherwise be required. \n\nYou can pass `partial: true` for validation to succeed in these scenarios:\n\n```typescript\nconst data = {\n    \"releaseDate\": '2006-10-06'\n}\n\nconst movieDto = await MovieDto.parse(data, {partial: true});\n```\n\n## Formatting Objects\n\nYou can also format internal data types to JSON data that can be returned in an HTTP response.\n\nA common example is model instances originating from an ORM:\n\n```typescript\nconst movie = await repo.fetchMovie(45).join('director')\nconst jsonData = await MovieDto.format(movie);\nreturn HttpResponse(jsonData);\n```\n\nSpecial types, like JavaScript's Date object, will be converted to JSON compatible output:\n```json\n{\n    \"title\": \"The Departed\",\n    \"releaseDate\": \"2006-10-06\",\n    \"director\": {\"name\": \"Martin Scorsese\"}\n}\n```\n\nAny internal properties not specified will be ommitted from the formatted output.\n\n# Fields\n\nFields handle converting between primitive values and internal datatypes. They also deal with validating input values. They are attached to a `DTObject` using the `bind(options)` static method. \n\nAll field types accept some core options:\n\n```typescript\ninterface BaseFieldOptions {\n    required?: boolean;  \n    allowNull?: boolean;\n    readOnly?: boolean;  \n    writeOnly?: boolean; \n    default?: any;\n    partial?: boolean;\n    formatSource?: string;\n    ignoreInput?: boolean;\n    context?: {[key: string]: any};\n}\n```\n\n| Option      | Description                         | Default |\n| ----------- | ---------------------------------- |  ------- |\n| required    | Whether an input value is required | true |\n| allowNull   | Whether null input values are allowed | false |\n| readOnly    | If true, any input value is ignored during parsing, but is included in the output format | false |\n| writeOnly   | If true, the field's value is excluded from the formatted output, but is included in parsing | false |\n| default     | The default value to use during parsing if none is present in the input | n/a |\n| formatSource  | The name of the attribute that will be used to populate the field, if different from the formatted field name name | n/a  |\n| ignoreInput  | Whether to always return the provided `default` when parsing and ignore the user-provider input. | false  |\n| context  | A container for additional data that'd be useful during parsing or formatting. A common scenario is to pass in an HTTP request object. | n/a  |\n\n## StringField: `string`\n\n- Parses input to _strings_. Coerces numbers, other types invalid. \n- Formats all value types to _strings_.\n\n```typescript\ninterface StringOptions extends BaseFieldOptions {\n    allowBlank?: boolean;\n    trimWhitespace?: boolean;\n    maxLength?: number;\n    minLength?: number;\n    pattern?: RegExp,\n    format?: 'email' | 'url'\n}\n```\n| Option      | Description                         | Default |\n| ----------- | ---------------------------------- |  ------- |\n| allowBlank    | If set to true then the empty string should be considered a valid value. If set to false then the empty string is considered invalid and will raise a validation error. | false |\n| trimWhitespace   | If set to true then leading and trailing whitespace is trimmed.  | true |\n| maxLength    | Validates that the input contains no more than this number of characters. | n/a |\n| minLength   | Validates that the input contains no fewer than this number of characters. | n/a |\n| pattern     | A `Regex` that the input must match or a ParseError will be thrown. | n/a |\n| format  | A predefined format that the input must conform to or a ParseError will be thrown. Supported values: `email`, `url`. | n/a  |\n\n## BooleanField: `boolean`\n\n- Parses input to _booleans_. Coerces certain bool-y strings. Other types invalid.\n- Formats values to _booleans_.\n\nTruthy inputs:\n```typescript\n['t', 'T', 'y', 'Y', 'yes', 'Yes', 'YES', 'true', 'True', 'TRUE', 'on', 'On', 'ON', '1', 1, true]\n```\n\nFalsey inputs:\n```typescript\n['f', 'F', 'n', 'N', 'no', 'No', 'NO', 'false', 'False', 'FALSE', 'off', 'Off', 'OFF', '0', 0, 0.0, false]\n```\n\n## NumberField: `number`\n\n- Parses input to _numbers_. Coerces numeric strings. Other types invalid.\n- Formats values to _numbers_.\n\n```typescript\ninterface NumberOptions extends BaseFieldOptions {\n    maxValue?: number;\n    minValue?: number;\n}\n```\n\n| Option      | Description                         | Default |\n| ----------- | ---------------------------------- |  ------- |\n| maxValue   | Validate that the number provided is no greater than this value. | n/a |\n| minValue   | Validate that the number provided is no less than this value. | n/a |\n\n\n\n## DateTimeField: `Date`\n\n- Parses input to _`Date` instances_. Coercing date-ish strings using `Date.parse()`. \n- Formats values to _strings_ with `Date.toISOString()`.\n\n```typescript\ninterface DateTimeFieldOptions extends BaseFieldOptions {\n    maxDate?: Date;\n    minDate?: Date;\n}\n```\n\n| Option      | Description                                                  | Default |\n| ----------- | ---------------------------------------------------------------- | --- |\n| maxDate   | Validate that the date provided is no later than this date. | n/a |\n| minDate   | Validate that the date provided is no earlier than this date.    | n/a |\n\n\n## ArrayField: `Array\u003cT\u003e`\n\n- Parses and formats a list of fields or nested objects.\n\n```typescript\ninterface ArrayOptions extends BaseFieldOptions {\n    items: BaseField | DTObject;\n    maxLength?: number;\n    minLength?: number;\n}\n```\n\n| Option      | Description                                                  | Default |\n| ----------- | ---------------------------------------------------------------- | --- |\n| items   | A bound field or object | n/a |\n| maxLength   | Validates that the array contains no fewer than this number of elements. | n/a |\n| minLength   | Validates that the list contains no more than this number of elements.    | n/a |\n\n\nExamples:\n\n```typescript\nclass ActionDto extends DTObject {\n    name = String.bind()\n    timestamp = DateTimeField.bind()\n}\n\nclass UserDto extends DTObject {\n    actions = ArrayField.bind({ items: ActionDto.bind() })\n    emailAddresses = ArrayField.bind({ items: StringField.bind() })\n}\n```\n\n## CombineField: `oneOf`, `anyOf`\n\nFields or objects can be composed together, using JSON Schema's `oneOf` or `anyOf` to parse \u0026 validate with `OR` or `XOR` logic. That is, the input must match *at least one* (`anyOf`) or *exactly* one (`oneOf`) of the specified sub-fields.\n\n```typescript\ninterface CombineField extends BaseFieldOptions {\n    anyOf?: Array\u003cBaseField | DTObject\u003e;\n    oneOf?: Array\u003cBaseField | DTObject\u003e;\n}\n```\n\n| Option      | Description                                                  | Default |\n| ----------- | ---------------------------------------------------------------- | --- |\n| anyOf   | The supplied data must be valid against any (one or more) of the given subschemas. | n/a |\n| oneOf   | The supplied data must be valid against exactly one of the given subschemas. | n/a |\n\n**Example: `oneOf`**\n\n```typescript\nimport { CombineField } from \"dto-classes\";\n\n// friendSchema must match a person or dog object, but not both\n\nclass Person extends DTObject {\n    name = StringField.bind()\n    hasTwoLegs = BooleanField.bind()\n}\n\nclass Dog extends DTObject {\n    name = StringField.bind()\n    hasFourLegs = BooleanField.bind()\n}\n\nconst friendSchema = new CombineField({\n    oneOf: [\n        Person.bind(),\n        Dog.bind()\n    ]\n});\n```\n\n**Example: `anyOf`**\n\n```typescript\n// Quantity must be between 1-5 or 50-100\n\nclass InventoryItem extends DTObject {\n    quantity = CombineField.bind({\n        anyOf: [\n            NumberField.bind({ minValue: 1, maxValue: 5 }),\n            NumberField.bind({ minValue: 50, maxValue: 100 })\n        ]\n    })\n}\n```\n\n## Nested Objects: `DTObject`\n\n`DTObject` classes can be nested under parent `DTObject` classes and configured with the same core `BaseFieldOptions`:\n\n```typescript\nimport { DTObject, StringField, DateTimeField } from 'dto-classes';\n\n\nclass Plot extends DTObject {\n    content: StringField.bind()\n}\n\nclass MovieDto extends DTObject {\n    title = StringField.bind()\n    plot = Plot.bind({required: false, allowNull: true})\n}\n```\n\n# Error Handling\n\nIf parsing fails for any reason -- the input data could not be parsed or a validation constraint failed -- a `ParseError` is thrown.\n\nThe error can be inspected:\n\n```typescript\nclass ParseError extends Error {\n  issues: ValidationIssue[];\n}\n\ninterface ValidationIssue {\n    path: string[]; // path to the field that raised the error\n    message: string; // English description of the problem\n}\n```\n\nExample:\n```typescript\nimport { ParseError } from \"dto-classes\";\n\n\nclass DirectorDto extends DTObject {\n    name = StringField.bind()\n}\n\nclass MovieDto extends DTObject {\n    title = StringField.bind()\n    director = DirectorDto.bind(),\n}\n\ntry {\n    const movieDto = await MovieDto.parse({\n        title: 'Clifford', \n        director: {}\n    });\n} catch (error) {\n    if (error instanceof ParseError) {\n        console.log(error.issues);\n        /* [\n            {\n                \"path\": [\"director\", \"name\"],\n                \"message\": \"This field is required\"\n            }\n        ] */\n    }\n}\n\n```\n\n# Custom Parsing/Validation\n\nFor custom validation and rules that must examine the whole object, methods can be added to the `DTObject` class.\n\nTo run the logic after coercion, use the `@AfterParse` decorator.\n\n```typescript\nimport { AfterParse, BeforeParse, ParseError } from \"dto-classes\";\n\nclass MovieDto extends DTObject {\n    title = StringField.bind()\n    director = DirectorDto.bind()\n\n    @AfterParse()\n    rejectBadTitles() {\n        if (this.title == 'Yet Another Superhero Movie') {\n            throw new ParseError('No thanks');\n        }\n    }\n}\n```\n\nThe method can modify the object as well:\n\n```typescript\nimport { AfterParse, BeforeParse, ParseError } from \"dto-classes\";\n\nclass MovieDto extends DTObject {\n    title = StringField.bind()\n    director = DirectorDto.bind()\n\n    @AfterParse()\n    makeTitleExciting() {\n        this.title = this.title + '!!';\n    }\n}\n```\n\n# Custom Formatting\n\nOverride the static `format` method to apply custom formatting.\n\n```typescript\nimport { AfterParse, BeforeParse, ParseError } from \"dto-classes\";\n\nclass MovieDto extends DTObject {\n    title = StringField.bind()\n    director = DirectorDto.bind()\n\n    static format(value: any) {\n        const formatted = super.format(value);\n        formatted['genre'] = formatted['director']['name'].includes(\"Mike Judge\") ? 'comedy' : 'drama';\n        return formatted;\n    }\n}\n```\n\nA nicer way to expose computed values is to use the `@Format` decorator. The single argument (e.g. \"obj\") will always be \nthe full object initially passed to the static `format()` method:\n\n```typescript\nclass Person extends DTObject {\n    firstName = StringField.bind()\n    lastName = StringField.bind()\n\n    @Format()\n    fullName(obj: any) {\n        return `${obj.firstName} ${obj.lastName}`;\n    }\n}\n\nconst formattedData = await Person.format({\n    firstName: 'George',\n    lastName: 'Washington',\n});\n\nexpect(formattedData).toEqual({ \n    firstName: 'George', \n    lastName: 'Washington', \n    fullName: 'George Washington' \n});\n```\n\nYou can customize the formatted field name by passing `{fieldName: string}` to the decorator:\n\n```typescript\nclass Person extends DTObject {\n    firstName = StringField.bind()\n    lastName = StringField.bind()\n\n    @Format({fieldName: 'fullName'})\n    makeFullName(obj: any) {\n        return `${obj.firstName} ${obj.lastName}`;\n    }\n}\n\n/*\n{ \n    firstName: 'George', \n    lastName: 'Washington', \n    fullName: 'George Washington' \n}\n*/\n```\n\n# Recursive Objects\n\nTo prevent recursion errors (eg \"Maximum call stack size exceeded\"), wrap nested self-refrencing objects in a `Recursive` call:\n\n```typescript\nimport { ArrayField, Rescursive } from \"dto-classes\";\n\nclass MovieDto extends DTObject {\n    title = StringField.bind()\n    director = DirectorDto.bind()\n    sequels: ArrayField({items: Recursive(MovieDto)})\n}\n```\n\n# Standalone Fields\n\nIt's possible to use fields outside of `DTObject` schemas:\n\n```typescript\nimport { DateTimeField } from \"dto-classes\";\n\nconst pastOrPresentday = DateTimeField.parse('2022-12-25', {maxDate: new Date()});\n```\n\nYou can also create re-usable field schemas by calling the instance method `parseValue()`:\n\n```typescript\nconst pastOrPresentSchema = new DateTimeField({maxDate: new Date()});\n\npastOrPresentSchema.parseValue('2021-04-16');\npastOrPresentSchema.parseValue('2015-10-23');\n```\n\n# NestJS\n\n`DTObject` classes can integrate easily with NestJS global pipes. \n\nTwo ready-to-use examples are included.\n\n## Simple Validation Pipe\n\nCopy the pipe in [nestjs-examples/dto-validation-pipe.ts](nestjs-examples/dto-validation-pipe.ts) to your project.\n\n```typescript\nasync function bootstrap() {\n  const app = await NestFactory.create(AppModule);\n  app.useGlobalPipes(new DTOValidationPipe());\n  await app.listen(3000);\n}\nbootstrap();\n```\n\n## Validation Pipe with Request Context\n\nTo implement more complex validation it's often useful to be able to access the current HTTP request object. For example, knowing the current user could affect whether validation succeeds. Or maybe you want to implement a hidden field that always returns the current user.\n\nCopy the pipe in [nestjs-examples/dto-context-validation-pipe.ts](nestjs-examples/dto-context-validation-pipe.ts) to your project.\n\nEach request will construct its own pipe with the current request object so the pipe must be configured as a provider:\n\n```typescript\n@Module({\n  imports: [\n    UsersModule\n  ],\n  controllers: [],\n  providers: [\n    {\n        provide: APP_PIPE,\n        useClass: DTOContextValidationPipe,\n    }\n  ],\n})\nexport class AppModule { }\n```\n\nYou can now easily set up a hidden input field that always returns the authenticated user of the request:\n\n```typescript\nimport { BaseField, BaseFieldOptions, ParseReturnType } from 'dto-classes';\nimport { User } from 'path-to-entities/user.entity';\n\n\nexport class CurrentUserField\u003cT extends BaseFieldOptions\u003e extends BaseField {\n    _options: T;\n\n    constructor(options?: T) {\n        super(options);\n        this._options.ignoreInput = true;\n    }\n\n    public async parseValue(value: any): ParseReturnType\u003cUser, T\u003e {\n        return this.getDefaultParseValue();\n    }\n\n    async getDefaultParseValue(): Promise\u003cany\u003e {\n        const user = await this._context.request.fetchUser();\n        return user;\n    }\n}\n\n```\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Frsinger86%2Fdto-classes","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Frsinger86%2Fdto-classes","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Frsinger86%2Fdto-classes/lists"}