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 🙏

© 2025 – Pkg Stats / Ryan Hefner

@webf/rule

v1.0.1

Published

Business rule validation library

Downloads

344

Readme

Simple business validation library.

The @webf/rule is a simple library to write declarative business-validation rules. For schema validations, use Zod, Joi or other schema validation library. Some features:

  • Simple to use (Only three core APIs)
  • Composable and declarative

Table of Content

Installation

npm install --save @webf/rule@latest

Usage

Create a simple business rule:

import { Rule } from '@webf/rule';

// Step 1: Create a validator class.
export class DateShouldBeFuture extends Rule {
  /** Provider the `apply` method **/
  apply(date: Date): boolean {
    return compareDate(date, new Date()) >= 0;
  }
}

// Create a higher-order validator class that has depedencies.
export class AllowThisPastDate extends Rule {
  constructor(startDate: Date) {
    this.#startDate = startDate;
  }

  /** Async validator works too. */
  async apply(date: Date): Promise<boolean> {
    date.getTime() === date.getTime();
  }
}

Now, you are ready to use it using the test function:

import { test } from '@webf/rule';

// Step 2: Apply the validation rules.
type Payload = {
  date: Date;
  name: string;
};

async function validatePayload(payload: Payload) {
  const { date } = payload;

  // Some random past date
  const pastDate = new Date(new Date().getTime() - (24 * 3600 * 1000));

  try {
    // Throws if the validation fails
    await test(date, DateShouldBeFuture, new AllowThisPastDate(pastDate));
  } catch (e) {
    if (e instanceof AggregateError) {
      // Each error is instance of `RuleError`.
      console.log(e.errors);
    }
  }
}

The test function takes variadic number of parameters where first parameter is the data to validate and rest of the parameters are either Validator classes or instance of validator classes. Use the instance of validator class if you have additional inputs that need to be made available when test calls the validator's apply method.

If you need to run multiple validators and catch all the errors at once, you can ues withCatch function. The check function returned by withCatch simply adds the catch wrapper and collects all the errors into a single list.

import { withCatch } from '@webf/rule';

async function validatePayload(payload: Payload) {
  const { date, name } = payload;

  // Some random past date
  const pastDate = new Date(new Date().getTime() - (24 * 3600 * 1000));

  const { check, rejectIfError } = withCatch();

  // Does not throw if any error
  await check(date, DateShouldBeFuture, new AllowThisPastDate(pastDate));
  await check(name, NameShouldNotBeTaken);

  // If previous invocation of `check` function created errors then, throw.
  rejectIfError();
}

Writing rules

A rule is basically an object of two fields key and apply function:

type IRule<T> = {
  key: string;
  apply(value: T): boolean | Promise<boolean>;
}

The key is a error key to identify the rule at runtime and apply is a function that should resolve to boolean or Promise<boolean> value. The rule work on one data type of of data and validates it. You can create a rule using object literal.

const MyRule = {
  key: 'MyRule',
  apply(value) {
    return value > 0;
  },
};

Or, you can use the base Rule class that automatically uses the class name as its key at runtime. This is the recommended way to write the rules as it also makes it easy to pass additional dependencies that a rule may need via constructor function.

import { Rule } from '@webf/rule';

export class MyRule extends Rule {
  apply(value) {
    return value >= 0;
  }
}

Dependency injection

If your rule depends on more than one input for validation, e.g. another value to compare or pass DB client (of course, you should try to keep business logic as pure as possible), then you can use constructor function:

import { Rule } from '@webf/rule';

export class MyRule extends Rule {
  constructor(db) {
    super();
    this.db = db;
  }

  await apply(value) {
    const toCompare = await db.getValue();

    return value >= toCompare;
  }
}