protectron
v0.0.1-alpha.16
Published
![Protectron banner](https://gitlab.sandor-its.de/julian.lang/protectron/-/raw/main/docs/media/banner.svg)
Downloads
5
Readme
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;
}
}