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
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);
}
}
API reference
Function signatures
There is available one function with two overloads:
function transformAndValidate<T extends PlainObject>(classType: ClassType<T>, jsonString: string, options?: TransformValdiationOptions): Promise<T>;
function transformAndValidate<T extends PlainObject>(classType: ClassType<T>, object: PlainObject, options?: TransformValdiationOptions): Promise<T>;
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 with some properties (not empty - {}
). PlainObject
is a defined as normal JS object type but with some properties defined, to provide compile-time error when e.g. number is passed as parameter:
type PlainObject = {
[property: string]: any;
}
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!