MichalLytek / class-transformer-validator

A simple plugin for class-transformer and class-validator which combines them in a nice and programmer-friendly API.
MIT License
200 stars 19 forks source link
javascript typescript validation validator

class-transformer-validator

npm version Dependency Status devDependency Status peerDependency Status

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";

// declare the class using class-validator decorators
class User {
  @IsEmail()
  public email: string;

  public hello(): string {
    return "World!";
  }
}

// then load the JSON string from any part of your app
const userJson: string = loadJsonFromSomething();

// transform the JSON to class instance and validate it correctness
transformAndValidate(User, userJson)
  .then((userObject: User) => {
    // now you can access all your class prototype method
    console.log(`Hello ${userObject.hello()}`); // prints "Hello World!" on console
  })
  .catch(err => {
    // here you can handle error on transformation (invalid JSON)
    // or validation error (e.g. invalid email property)
    console.error(err);
  });

You can also transform and validate plain JS object (e.g. from express req.body). Using ES7 async/await syntax:

async (req, res) => {
  try {
    // transform and validate request body
    const userObject = await transformAndValidate(User, req.body);
    // infered type of userObject is User, you can access all class prototype properties and methods
  } catch (err) {
    // your error handling
    console.error(err);
  }
};

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 {
    // transform and validate request body - array of User objects
    const userObjects = await transformAndValidate(User, req.body);
    userObjects.forEach(user => console.log(`Hello ${user.hello()}`));
  } catch (err) {
    // your error handling
  }
};

API reference

Function signatures

There is available the transformAndValidate function with three overloads:

function transformAndValidate<T extends object>(
  classType: ClassType<T>,
  jsonString: string,
  options?: TransformValidationOptions,
): Promise<T | T[]>;
function transformAndValidate<T extends object>(
  classType: ClassType<T>,
  object: object,
  options?: TransformValidationOptions,
): Promise<T>;
function transformAndValidate<T extends object>(
  classType: ClassType<T>,
  array: object[],
  options?: TransformValidationOptions,
): Promise<T[]>;

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 = (await transformAndValidate(
  User,
  JSON.stringify([{ email: "test@test.test" }]),
)) as User[];

Or you can just check the type in runtime using Array.isArray method.

Synchronous transformation and validation

If you need sync validation, use transformAndValidateSync function instead (available since v0.4.0). It will synchronously return T or T[], not a Promise.

Parameters and types

type ClassType<T> = {
  new (...args: any[]): T;
};
interface TransformValidationOptions {
  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 powerful than it was showed in the simple usage sample, so go to their github page and check out they capabilities!

Release notes

0.9.1

0.9.0

0.8.0

0.7.1

0.6.0

0.5.0

0.4.1

0.4.0

0.3.0

0.2.0

0.1.1

0.1.0