npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

class-handler

v1.0.0

Published

Decorators to help with class handling

Downloads

19

Readme

codecov npm downloads Mutation testing badge

Provides decorators to help with class handling. Uses validator. Made with TypeScript, compiled to common JavaScript with d.ts files. Extensively tested with jest and stryker.

How to install

NPM:

npm i class-handler

YARN:

yarn add class-handler

Property Decorators

The library provides a few ready-to-use property decorators, as well as tools to easily build your own. Currently we only have validation decorators, which have 2 ways of working:

  • If you don't use the CatchMany class decorator, your instances will be validated by your decorators as soon as you instantiate them, throwing the first error that is found.

  • If you use property decorators along with the CatchMany decorator, your errors will be stored within each instance, and the errors will only be thrown when you call the function "validateInstance" for each given instance.

Example 1: without CatchMany

import { NotNull } from "class-handler";

class SomeClass {
  @NotNull({ error: "some-error" })
  someField: string;

  constructor(someField?: string) {
    this.someField = someField;
  }
}

let exception;

try {
  new SomeClass();
} catch (error) {
  exception = error;
}

console.log(exception); // { error: "some-error" }

Example 2: with CatchMany

import {
  NotNull,
  CatchMany,
  StringType,
  validateInstance,
} from "class-handler";

@CatchMany({ errorMessages: [] }, "errorMessages")
class SomeClass {
  @NotNull("some field should not be null")
  @StringType("some field should be a string type")
  someField?: any;

  constructor(someField?: any) {
    this.someField = someField;
  }
}

let exception;
const someInstance = new SomeClass();

try {
  validateInstance(someInstance);
} catch (error) {
  exception = error;
}

console.log(exception); // { errorMessages: ["some field should be a string type", "some field should not be null"] }

Built in property decorators

| Decorator | Error condition | | ------------------- | ---------------------------------------------------------------------------------------------- | | NotNull | null, undefined or empty string | | Email | not matching the email string pattern ([email protected]) | | StringType | not being a string type according to typescript/javascript | | NumberType | not being a number type according to typescript/javascript | | BooleanType | not being a boolean type according to typescript/javascript | | ArrayType | not being an array according to typescript/javascript | | IncludedInArray | not being an item of the given array (first parameter) | | NotIncludedInArray | being an item of the given array (first parameter) | | JsonString | not being a string parsable to a JSON object/array | | NumberGreaterThan | not being a number or being a number less or equal than a given threshold (first parameter) | | NumberLessThan | not being a number or being a number greater or equal than a given threshold (first parameter) | | StringMatchingRegex | not being a string or don't matching the given regex (first parameter) | | NumericString | not being a string or being a string with non-numeric chars | | AlphanumericString | not being a string or being a string with non-alphanumeric chars | | Integer | not being a number or not being an integer |

CustomValidation decorator

The CustomValidation decorator receives a condition, which is a function that receives the value (its only argument) of type any, returning true for the error case and false for success.

Example

import { CustomValidation } from "class-handler";

const isLessThanTenValidation = (value: any) => value < 10;

class SomeClass {
  @CustomValidation(isLessThanTenValidation, { error: "Value is less than 10" })
  someField: number;

  constructor(someField: number) {
    this.someField = someField;
  }
}

let exception: any;

try {
  new SomeClass(5);
} catch (error) {
  exception = error;
}

console.log(exception); // { error: "Value is less than 10" }

validationDecorator function

With the validationDecorator function, you can easily create your own property validation decorator. The function receives 2 arguments: the first one is the validation function/callback, exactly like in the CustomValidation decorator, and the second one is the error you want to throw, which can be an object, a string, an Error instance, or a callback function that receives 2 string parameters, class name and class property, and returns a error message (string).

Example

import { validationDecorator } from "class-handler";

const isLessThanTenValidation = (value: any) => value < 10;

const GreaterThanTen = validationDecorator(isLessThanTenValidation, {
  error: "Value is less than 10",
});

class SomeClass {
  @GreaterThanTen
  someField: number;

  constructor(someField: number) {
    this.someField = someField;
  }
}

let exception: any;

try {
  new SomeClass(5);
} catch (error) {
  exception = error;
}

console.log(exception); // { error: "Value is less than 10" }

Another way to use the validationDecorator function is returning the function, instead of its result. This is useful in case you want to pass parameters to your own decorator.

Example

import { validationDecorator } from "class-handler";

const isLessThanTenValidation = (value: any) => value < 10;

function GreaterThanTen(error: Object | string | Error) {
  return validationDecorator(isLessThanTenValidation, error);
}

class SomeClass {
  @GreaterThanTen({
    error: "Value is less than 10",
  })
  someField: number;

  constructor(someField: number) {
    this.someField = someField;
  }
}

let exception: any;

try {
  new SomeClass(5);
} catch (error) {
  exception = error;
}

console.log(exception); // { error: "Value is less than 10" }

Both of these alternative decorators work the same way as the ready-to-use decorators, including with and without the CatchMany decorator.

Class Decorators

Currently we only have 1 class decorator, which is the CatchMany. This decorator modify the behaviour of the property decorators.

Without the CatchMany decorator, the validation decorators will throw the first error they found as soon as the class is instantiated.

With the CatchMany decorator, the errors will be stored in each given instance at the moment they are instantiate, in the model you defined. The errors will be thrown when you call the validateInstance function, passing the given instance as the parameter.

The first CatchMany argument is the error object you want to throw in case of error(s). It's important to notice that one of this object fields must be an array. Each property decorator that cactches an error will push its error string into that array.

That means that when you use the CatchMany decorator, you must pass only strings for your property decorator. If you use the CatchMany decorator and pass an Object for your property decorators, you'll receive an error.

For usage examples, check "Example 1: without CatchMany" and "Example 2: with CatchMany" at the Property Decorators section.

Contact