data-transfer-object
Data Transfer Object class built on TypeStacks's class-validator
. Allows you to build a DTO class that automatically validates input from outside sources and ensures its shape is correct.
Table of contents
Installation
For Node.js and bundlers (Webpack, Rollup, etc)
npm i data-transfer-object
yarn add data-transfer-object
For browsers (script tag)
UMD builds aren't available yet. Rollup builds are planned for the future.
Usage
Create a DTO class by importing DataTransferObject
, extending it with your custom properties, and using the appropriate decorators. This package re-exports all decorators and functions from TypeStack's class-validator
.
import { DataTransferObject, IsString } from 'data-transfer-object';
class MyDto extends DataTransferObject {
@IsString()
myString: string;
}
Once your class is defined, you can instantiate it, pass your input into it, and validate it:
const input = new MyDto({ myString: 12 });
const errors = input.validate();
console.log(errors);
[
{
target: { myString: 12 },
value: 12,
property: 'myString',
children: [],
constraints: { isString: 'myString must be a string' },
},
];
Validating it will also silently drop all unknown properties from the input:
const input = new MyDto({ myString: 'a', myOtherString: 'b' });
const errors = input.validate();
console.log(errors);
console.log(input);
Take a look at class-validator
's documentation to get information on all available validators and validation options.
TypeScript notes
Note that when using TypeScript with "strict": true
, you must use non-null assertions (!:
) when declaring class properties. Also, experimentalDecorators
and emitDecoratorMetadata
must be set to true
in your tsconfig.json
.
Documentation
The most up-to-date documentation for all exported items from this package is automatically generated from code and available at https://danielegarciav.github.io/data-transfer-object/.
Example
In the following example, we have an Express application that lets us sign up users. In order to validate input from the web app client, we create a data transfer object representing the input data, and attach our desired validators:
import { DataTransferObject, IsString, Length, MinLength } from 'data-transfer-object';
export class UserSignupInput extends DataTransferObject {
@IsString()
@Length(2, 36, {
message: 'username must be 2-36 characters long',
})
username!: string;
@IsString()
@MinLength(8, {
message: 'password must be at least 8 characters long',
})
password!: string;
}
The Express request handler in our example:
import { Request, Response } from 'express';
import { User } from './models';
import { UserSignupInput } from './input-dtos';
export async function signup(req: Request, res: Response): {
const input = new UserSignupInput(req.body);
const errors = input.validate();
const asyncErrors = await input.validateAsync();
if (errors.length) {
return res.status(400).json(errors);
}
await User.register(input);
const data = input.toJSON();
typeof input.validate === 'function';
typeof data.validate === 'undefined';
return res.status(200).json({ success: true });
}
Development
Check package.json to find scripts related to installing dependencies, building, testing, linting and generating documentation.
License
MIT