GithubHelp home page GithubHelp logo

stechy1 / class-transformer-validator Goto Github PK

View Code? Open in Web Editor NEW

This project forked from michallytek/class-transformer-validator

0.0 1.0 0.0 295 KB

A simple plugin for class-transformer and class-validator which combines them in a nice and programmer-friendly API.

License: MIT License

TypeScript 100.00%

class-transformer-validator's Introduction

IMPORTANT NOTE!

This repository is a fork of the original class-transformer-validator package.

class-transformer-validator

A simple plugin for @nestjs/class-transformer and @nestjs/class-validator which combines them in a nice and programmer-friendly API.

Installation

Module installation

npm install @stechy1/class-transformer-validator --save

(or the short way):

npm i -S @stechy1/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 "@nestjs/class-validator";
import { transformAndValidate } from "@stechy1/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: "[email protected]" }]),
)) 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

  • 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 TransformValidationOptions {
  validator?: ValidatorOptions;
  transformer?: ClassTransformOptions;
}

You can use it to pass options for @nestjs/class-validator (more info) and for @nestjs/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.2

0.9.1

  • widen class-transformer peer dependency version range to >=0.2.3
  • updated all dev dependencies

0.9.0

  • bump class-validator peer dependency to version >=0.12.0
  • updated TypeScript dependency to version ^3.9.5
  • updated all dev dependencies

0.8.0

  • updated class-transformer dependency to version ^0.2.3
  • updated class-validator dependency to version ^0.10.1
  • updated TypeScript dependency to version ^3.6.3
  • built code is now emitted as ES2015 (dropped es5 support)
  • updated all dev dependencies

0.7.1

  • updated class-transformer dependency to version ^0.2.0

0.6.0

  • updated class-validator dependency to version ^0.9.1

0.5.0

  • remove deprecated TransformValdiationOptions interface (typo)
  • updated class-validator dependency to version ^0.8.1 and class-transformer to ^0.1.9

0.4.1

  • fix TransformValdiationOptions interface name typo (deprecate in favour of TransformValidationOptions)

0.4.0

  • added transformAndValidateSync function for synchronous validation
  • changed return type for JSON's transform and validation to Promise of T or T[]
  • updated 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
  • updated 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

class-transformer-validator's People

Contributors

michallytek avatar quezak avatar stechy1 avatar

Watchers

 avatar

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.