@kangojs/class-validation

Validate and transform request data using classes in KangoJS.

Usage no npm install needed!

<script type="module">
  import kangojsClassValidation from 'https://cdn.skypack.dev/@kangojs/class-validation';
</script>

README

@kangojs/class-validation

Validate and transform request data using classes in KangoJS.

🤔 About

Easily transform and validate Express request data using classes with class-transformer and class-validator.

This package has been built specifically for use with KangoJS. While you could potentially use this package without KangoJS, it isn't 'officially' supported at this time.

💥 Features

  • Quickly integrate with KangoJS's validation system. Focus on writing project code not sorting request validation logic.
  • Incoming request data is automatically transformed and attached to the Express req object.
  • Use on both request body and query data.

🚀 Getting Started

Install the npm package:

npm install @kangojs/class-validation

Peer Dependencies:
@kangojs/class-validation is primarily just a wrapper around class-transformer and class-validator so you must install these two peer dependencies yourself in order to use this package.

👷 Usage

As @kangojs/class-validation has been built specifically for use with KangoJS it's pretty much just a case of dropping it in.

Setup Validation Middleware

When setting up KangoJS you can simply pass the results of createBodyValidator and createQueryValidator into the configuration options like so:

import express from 'express';
import { KangoJS } from '@kangojs/kangojs';
import { createBodyValidator, createQueryValidator } from "@kangojs/class-validation";

const app = express();

const kangoJS = new KangoJS({
    controllerFilesGlob: "src/modules/*.controller.ts",
    globalPrefix: "/api/v1",
    bodyValidator: createBodyValidator(),
    queryValidator: createQueryValidator(),
});
await kangoJS.boostrap(app);

You can also pass options to the create validator functions. Here are the possible options:

Attribute Type Description
classTransformerOptions TransformerOptions (from class-transformer) Options for class-transformer
classValidatorOptions ValidatorOptions (from class-validator) Options for class-validator
errorHandler (error: Error, res?: Response) => Promise<void> Allows you to overwrite the default behaviour on validation error.

Add Request Validation

Create a class DTO using class-validator. For example:

import { IsString, IsEmail, MinLength } from 'class-validator';

export class CreateUserDTO {
    @IsEmail()
    email: string;
    
    @IsString()
    username: string;

    @IsString()
    @MinLength(12)
    password: string;
}

Add your DTO to the @Route decorator provided by KangoJS:

import { Request, Response, NextFunction } from 'express';
import { Controller, Route, HTTPMethods } from '@kangojs/kangojs';
import { RequestWithDto } from '@kangojs/class-validation';
import { UserAddDTO } from './user-add.dto';

@Controller('/users')
export class UserController {
    @Route({
        httpMethod: HTTPMethods.POST,
        bodyShape: UserAddDTO
    })
    async addUser(req: RequestWithDto, res: Response, next: NextFunction) {
        const userAddDto = <UserAddDTO> req.bodyDto;
        
        return res.send('You have just attempted add a user via /users [POST].');
    }
}

This process is exactly the same for query data except you use the queryShape route option and req.queryDto to access the transformed data instead.

Default Behaviour

This package has sensible defaults for validation options and error handling.

Validation

The default options for class-validator are as follows:

{
    whitelist: true,
    forbidNonWhitelisted: true,
    forbidUnknownValues: true,
    validationError: {
        target: false
    }
}

Error Handling

When validation fails the default behaviour is to return a 400 response with the following body data:

{
    "statusCode": 400,
    "message": "The supplied body data did not pass validation.",
    "reason": "first error reason from class-validator if applicable"
}

🧰 Other KangoJS Packages

For all available KangoJS packages check out this list.

💬 Feedback & Contributions

I'm open to feedback and contributions. Feel free to raise an issue or suggest improvements and features.

📝 License

This project is licensed under the terms of the MIT license.