0.0.1-alpha.16 • Published 2 years ago

protectron v0.0.1-alpha.16

Weekly downloads
-
License
MIT
Repository
-
Last release
2 years ago

Protectron banner

Protectron

Protectron is a method guard decorator that helps you asserting the pre- and post conditions of your methods.

The aim is to help you find bugs earlier and easier throughout your code.

Usage

You can either use the built-in guards by importing import { Expect } from 'protectron' or you can write your own guards by implementing the IMethodGuard interface:

import {
  Expect,
  Protectron,
  HasTypeGuard,
  IGuardReturnValue,
  IMethodGuard,
  IPostCallEnv,
  IPreCallEnv,
} from "protectron";

class NotDivideByZero implements IMethodGuard {
  private static numberGuard = new HasTypeGuard(this.paramName, "number");

  constructor(private paramName: string) {}

  checkArgs(env: IPreCallEnv): IGuardReturnValue {
    let error = NotDivideByZero.numberGuard.checkArgs(env);

    if (args[index] === 0) {
      error = `Expected the divisor not to be zero!`;
    }

    // can be either string, null or undefined
    // throws only when it is a string
    return error;
  }
  checkEntryState(env: IPreCallEnv): IGuardReturnValue {
    return;
  }
  checkExitState(env: IPostCallEnv): IGuardReturnValue {
    return;
  }
  checkReturnValue(env: IPostCallEnv): IGuardReturnValue {
    return;
  }
}

class Calculator {
  @Protectron({
    args: [Expect("a").toHaveType("number"), new NotDivideByZero("b")],
  })
  public divide(a: number, b: number): number {
    return a / b;
  }

  // above method is identical to:
  public divide(a: number, b: number): number {
    if (typeof a !== "number") {
      throw new Error(
        `Expected argument "a" to have type "number", but it is "${typeof a}"`
      );
    }
    if (b === 0) {
      throw new Error("Expected the divisor not to be zero!");
    }

    return a / b;
  }
}
0.0.1-alpha.16

2 years ago

0.0.1-alpha.15

2 years ago

0.0.1-alpha.14

2 years ago

0.0.1-alpha.13

2 years ago

0.0.1-alpha.12

2 years ago

0.0.1-alpha.11

2 years ago

0.0.1-alpha.10

2 years ago

0.0.1-alpha.9

2 years ago

0.0.1-alpha.8

2 years ago

0.0.1-alpha.7

2 years ago

0.0.1-alpha.6

2 years ago

0.0.1-alpha.5

2 years ago

0.0.1-alpha.4

2 years ago

0.0.1-alpha.2

2 years ago

0.0.1-alpha.1

2 years ago