Runtime input validation with kapow

Input validation can be a tedious process, but luckily there are many great libraries out there to help out, including Sindre Sorhus’ ow. Building on this powerful, yet lightweight tool it can now be taken a step further through the use of decorators. By including a @kapow() decorator with your requirements and a @validate decorator to enforce validation, you can gain the power of ow to perform validation at runtime with a clean syntax.

Installation

To get started with kapow, include it with your project through npm install:

$ npm install --save @livelysoftware/kapow

NOTE: Since this project does use decorators, you will need to enable experimentalDecorators in the compilerOptions section of your tsconfig.json file.

{
  "compilerOptions": {
    ...
    "experimentalDecorators": true
  }
}

Example

After installing the project and enabling experimentalDecorators you can begin to decorate and validate your class methods. On the top of your method be sure to include a @validate, then before each parameter you wish to validate include a @kapow() and pass your validation rules. At this time only two validation rules are supported, required and type, though more will come in the future. An example use of this library might look like this:


import { kapow, validate } from "@livelysoftware/kapow";

class MyClass {

  constructor() {}

  @validate
  add(
    @kapow({
      required: true,
      type: "number"
    }) a,
    @kapow({
      required: true,
      type: "number"
    }) b
  ) {
    /*
      If a and/or b are not provided and/or
      not of type "number" then an error will be thrown
    */
    return a + b;
  }

}

Ending thoughts

This project is super young and not at all production ready. There are many improvements to be made in terms of matching ow’s API as much as possible and reducing the decorators/code needed to have this project work in your code, but it will continue to improve. If you wish to contribute or have any feedback, please don’t hesitate to reach out and/or submit a issue or pull request.