class-transformer-validator
A simple plugin for class-transformer and class-validator which combines them in a nice and programmer-friendly API.
Installation
Module installation
npm install class-transformer-validator --save
(or the short way):
npm i -S class-transformer-validator
Peer dependencies
This package is only a simple plugin/wrapper, so you have to install the required modules too because it can't work without them. See detailed installation instruction for the modules installation:
Usage
The usage of this module is very simple.
import { IsEmail } from 'class-validator';
import { transformAndValidate } from "class-transformer-validator";
class User {
@IsEmail()
public email: string;
public hello(): string {
return "World!";
}
}
const userJson: string = loadJsonFromSomething();
transformAndValidate(User, userJson)
.then((userObject: User) => {
console.log(`Hello ${userObject.hello()}`);
})
.catch(error => {
console.err(error);
});
You can also transform and validate plain JS object (e.g. from express req.body). Using ES7 async/await syntax:
async (req, res) => {
try {
const userObject = await transformAndValidate(User, req.body);
} catch (error) {
console.err(error);
}
}
And since release 0.3.0
you can also pass array of objects - all of them will be validated using given class validation constraints:
async (req, res) => {
try {
const userObjects = await transformAndValidate(User, req.body);
userObjects.forEach(user => console.log(`Hello ${user.hello()}`));
} catch (error) {
}
}
API reference
Function signatures
There is available the transformAndValidate
function with three overloads:
function transformAndValidate<T extends object>(classType: ClassType<T>, jsonString: string, options?: TransformValdiationOptions): Promise<T|T[]>;
function transformAndValidate<T extends object>(classType: ClassType<T>, object: object, options?: TransformValdiationOptions): Promise<T>;
function transformAndValidate<T extends object>(classType: ClassType<T>, array: object[], options?: TransformValdiationOptions): Promise<T[]>;
If you need sync validation, use transformAndValidateSync
function instead (since v0.4.0).
Be aware that if you validate json string, the return type is a Promise
of T
or T[]
so you need to assert the returned type if you know the shape of json:
const users = transformAndValidate(User, JSON.stringify([{ email: "test@test.test" }])) as User[];
Or you can just check in runtime using Array.isArray(obj)
method.
Parameters and types
classType
- an class symbol, a constructor function which can be called with new
type ClassType<T> = {
new (...args: any[]): T;
}
-
jsonString
- a normal string containing JSON
-
object
- plain JS object of type object
(introduced in TypeScript 2.2), you will have compile-time error while trying to pass number, boolean, null or undefined but unfortunately run-time error when passing a function
-
array
- array of plain JS objects like described above
-
options
- optional options object, it has two optional properties
interface TransformValdiationOptions {
validator?: ValidatorOptions;
transformer?: ClassTransformOptions;
}
You can use it to pass options for class-validator
(more info) and for class-transformer
(more info).
More info
The class-transformer and class-validator are more powerfull than it was showed in the simple usage sample, so go to their github page and check out they capabilities!
Release notes
0.4.0
- added
transformAndValidateSync
function for synchronous validation - changed return type for transform and validation JSON to
Promise
of T
or T[]
- bumped
class-validator
dependency to version ^0.7.2
and class-transformer
to ^0.1.7
0.3.0
- added support for transform and validate array of objects given class
- bumped
class-validator
dependency to version ^0.7.1
0.2.0
- changed object parameter type declaration to
object
(introduced in TS 2.2) - throwing error when passed array, undefined or null
0.1.1
0.1.0
- initial version with
transformAndValidate
function