@cowwoc/requirements
TypeScript icon, indicating that this package has built-in type declarations

3.4.0 • Public • Published

npm version build-status

checklist Fluent API for Design Contracts

API Changelog java

A fluent API for enforcing design contracts with automatic message generation.

✔️ Easy to use
✔️ Fast
✔️ Production-ready

To get started, add this dependency:

npm install --save @cowwoc/requirements@3.4.0

or pnpm:

pnpm add @cowwoc/requirements@3.4.0

The contents of the API classes depend on which modules are enabled.

Sample Code

import {requireThat} from "@cowwoc/requirements";


class Address
{
}

class PublicAPI
{
	constructor(name: string | null, age: number, address: Address | undefined)
	{
		// To validate user input, cast them to "unknown" prior to type-checks.
		requireThat(name as unknown, "name").isString().length().isBetween(1, 30);
		requireThat(age as unknown, "age").isNumber().isBetween(18, 30);

		// Methods that conduct runtime type-checks, such as isString() or isNotNull(), update the
		// compile-time type returned by getActual().
		const nameIsString: string = requireThat(name as unknown, "name").isString().getActual();
		const address: Address = requireThat(address as unknown, "address").isInstance(Address).getActual();
	}
}

class PrivateAPI
{
	public static toCamelCase(text): string
	{
		// Trusted input does not need to be casted to "unknown". The input type will be inferred
		// and runtime checks will be skipped. Notice the lack of isString() or isNumber() invocations
		// in the following code.
		assertThat(r => r.requireThat(name, "name").length().isBetween(1, 30));
		assertThat(r => r.requireThat(age, "age").isBetween(18, 30));
	}
}

Failure messages will look like this:

TypeError: name may not be null

RangeError: name may not be empty

RangeError: age must be in range [18, 30).
Actual: 15

Features

Getting Started

The best way to learn about the API is using your IDE's auto-complete engine. There are six entry points you can navigate from:

Best practices

  • Use requireThat() to verify pre-conditions of public APIs.
  • Use assertThat() to verify object invariants and method post-conditions. This results in excellent performance when assertions are disabled. Have your cake and eat it too!

Related Projects

License

Code licensed under the Apache License, Version 2.0: http://www.apache.org/licenses/LICENSE-2.0

Icons made by Flat Icons from www.flaticon.com is licensed by CC 3.0 BY

Package Sidebar

Install

npm i @cowwoc/requirements

Weekly Downloads

91

Version

3.4.0

License

Apache-2.0

Unpacked Size

1.44 MB

Total Files

229

Last publish

Collaborators

  • cowwoc