A human-readable, fast and boilerplate-free contract programming library for JavaScript.
Why would I want it?
- It reduces the boilerplate of writing assertion messsages to zero,
- Provides very intuitive and extensible DSL for writing assertions,
- Low core bundle size (22.5kB minified) and a way of bundling only needed assertions,
- Has zero runtime dependencies which greatly increases package security,
- It's TypeScript-friendly (contains its own
.d.ts
files).
npm install --save offensive
// node-style require
const { check } = require('offensive');
// es6-style default import
import check from 'offensive';
In order to minimize bundle payload, each assertion must be imported separately. It can be done during application bootup or in each file where specific assertion is used (importing an assertion multiple times is harmless).
// node-style require
require('offensive/assertions/aString/register');
// es6-style default import
import 'offensive/assertions/aString/register';
Programming offensively is about throwing exceptions a lot. As soon as corrupted state or illegal parameter is detected, program is crashed with a descriptive error message. This technique greatly helps in finding bugs at their cause.
import 'offensive/assertions/fieldThat/register';
import 'offensive/assertions/aNumber/register';
import check from 'offensive';
class Point2D {
/**
* @param init initializer object containing `x` and `y` properties.
*/
constructor(init) {
// Contract is satisfied if init contains
// `x` and `y` property of type number.
check(init, 'init')
.has.fieldThat('x', x => x.is.aNumber)
.and.fieldThat('y', y => y.is.aNumber)
();
this.x = init.x;
this.y = init.y;
}
}
Now, following erroneus call...
const point = new Point2D({ x: 'a', y: null });
...will result in throwing following exception.
ContractError: init.x must be a number (got 'a') and init.y be a number (got null)
at operatorContext (offensives/ContextFactory.js:34:33)
at new Point2D (example.js:16:7)
at Object.<anonymous> (example.js:22:15)
Alternatively, above contract could be implemented using multiple checks, but the error would only contain information about first failed check.
check(init, 'init').is.anObject();
check(init.x, 'init.x').is.aNumber();
check(init.y, 'init.y').is.aNumber();
Above examples use only .anObject
, .aNumber
and .fieldThat
assertions.
See full list of offensive.js built-in assertions.
Offensive programming is not applicable when collaborating with external components. A program should not crash in response to a bug in another program. Logging an error and trying to correct it by using default value or simply ignoring erroneus input would be a better way of handling such cases.
Following example is a fully functional HTTP-based ping server implemented using express.js with defensive checks on HTTP request implemented using offensive.js.
import * as express from 'express';
import * as bodyParser from 'body-parser';
import 'offensive/assertions/aString/register';
import 'offensive/assertions/fieldThat/register';
import check from 'offensive';
const app = express();
app.use(bodyParser.json());
// A simple ping service which reflects messages sent to it.
app.post('/ping', function (req, res, next) {
try {
// Contract is satisfied if body has a message which is a string
// (.propertyThat is an alias of .fieldThat assertion)
check(req.body, 'req.body')
.contains.propertyThat('message', message => message.is.aString)();
const { message } = body;
res.json({ message });
} catch (e) {
// In case contract is not satisfied, an instance
// of ContractError will be passed to next middleware.
next(e);
}
});
// Error handling middleware.
app.use(function (err, req, res, next) {
// Failed offensive.js assertions can be easily differentiated
// from other errors by checking error name.
switch (err.name) {
case 'ContractError':
// In case its an assertion from offensive.js
// HTTP status which indicates a client error is apropriate.
res.status(400);
// Could also be HTTP 412 Precondition Failed
// in case there's a need of being more specific.
// It's safe to reveil error message in response
// as it doesn't contain information about the contract
// and not about the implementation.
const { name, message } = err;
res.json({ error: `${name}: ${message}` });
break;
default:
// Any other error will result in HTTP 500 Internal Server Error.
res.status(500);
res.json({ 'error': 'InternalServerError: ${err.name}' });
break;
}
});
Above code presents defensive programming on the server side, but the same technique is applicable in the client. Client-server contract should be tested both, after receiving request from the client, and after receiving response from the server.
Table of Contents
function check<T>(testedValue : T, varName : string) : AssertionBuilder<T>;
Creates an instance of AssertionBuilder
. Methods of returned
instance add assertions to the builder. Requested assertions
will be checked against given testedValue after executing assertion
expression. In case some assertions fail, given name
will be used as part of error message.
import check from 'offensive';
...
check(arg, 'arg')...
interface AssertionBuilder<T> {
() : T;
}
Executes built assert expression. Returns testedValue if assertion succeeds.
Throws ContractError
in case it fails.
import 'offensive/assertions/length';
import check from 'offensive';
check(arg, 'arg')
.has.length(10)
(); // <- executes built assert expression
NOTE: Assertion will not be run unless call operator is invoked.
offensive.js contains following built-in assertions.
Table of Contents
.Null()
.Undefined()
.Empty()
.ofType(requiredType)
.aBoolean()
.aNumber()
.anInteger()
.aString()
.anObject()
.aFunction()
.anArray()
.anInstanceOf(RequiredClass)
.aDate()
.aRegExp()
.True()
.False()
.truthy()
.falsy()
.matches(regexp)
.anEmail()
.anIntegerString()
.equalTo()
.exactly()
.lessThan(rightBounds)
.lessThanOrEqualTo(rightBounds)
.greaterThan(leftBounds)
.greaterThanOrEqualTo(leftBounds)
.inRange(leftBounds, rightBounds)
.before(rightBounds, boundsVarName?)
.after(leftBounds, boundsVarName?)
.field(fieldName)
.fieldThat(fieldName)
.allFieldsThat(condition)
.method(methodName)
.length(requiredLength)
.oneOf(set, name)
.elementThat(index, assertName, condition)
.allElementsThat(assertName, condition)
Asserts that checked value is null
using ===
.
Typically used in combination with .not
operator.
check(arg, 'arg').is.not.Null();
Asserts that checked value is undefined
.
Typically used in combination with .not
operator.
check(arg, 'arg').is.not.Undefined();
Asserts that checked value is null
or undefined
.
Typically used in combination with .not
operator.
check(arg, 'arg').is.not.Empty();
Asserts that checked value is of requiredType by ivoking typeof
operator.
check(arg, 'arg').is.ofType('boolean')();
Asserts that checked value is a boolean by ivoking typeof
operator.
check(arg, 'arg').is.aBoolean();
Asserts that checked value is a number by ivoking typeof
operator.
check(arg, 'arg').is.aNumber();
Asserts that checked value is an integer by ivoking Number.isInteger
.
check(arg, 'arg').is.anInteger();
Asserts that checked value is a string by ivoking typeof
operator.
check(arg, 'arg').is.aString();
Asserts that checked value is an object by ivoking typeof
operator.
Be wary that this will be true also for array instances and null
.
Use .anArray
and .Null
in order to test for these
specific cases.
check(arg, 'arg').is.anObject();
Asserts that checked value is a function by ivoking typeof
operator.
check(arg, 'arg').is.aFunction();
Asserts that checked value is an array by invoking Array.isArray
.
check(arg, 'arg').is.anArray();
Asserts that checked value is a instance of RequiredClass, by
using instanceof
operator.
check(arg, 'arg').is.anInstanceOf(RegExp)();
Asserts that checked value is a instance of Date
, by
using instanceof
operator.
check(arg, 'arg').is.aDate();
Asserts that checked value is a instance of RegExp
, by
using instanceof
operator.
check(arg, 'arg').is.aRegExp();
Asserts that checked value is a boolean of value true
.
check(arg, 'arg').is.True();
Asserts that checked value is a boolean of value false
.
check(arg, 'arg').is.False();
Asserts that checked value is truthy (converts to true
).
check(arg, 'arg').is.truthy();
Asserts that checked value is falsy (converts to false
).
check(arg, 'arg').is.falsy();
Asserts that checked value fully matches given regexp.
check(arg, 'arg').matches(/[a-z]+/)();
Asserts that checked value is a valid email.
check(arg, 'arg').is.anEmail();
Asserts that checked value is a valid string form of an integer.
check(arg, 'arg').is.anIntegerString();
Asserts that checked value is equal to another.
Comparison is made with ==
(double equals) operator.
check(arg, 'arg').is.equalTo(100)();
Asserts that checked value is exactly the same as another.
Comparison is made with ===
(triple equals) operator.
check(arg, 'arg').is.exactly(instance)();
Asserts that checked value is less than rightBounds.
check(arg, 'arg').is.lessThan(100)();
Asserts that checked value is less than or equal to rightBounds.
check(arg, 'arg').is.lessThanOrEqualTo(100)();
Asserts that checked value is greater than leftBounds.
check(arg, 'arg').is.greaterThan(0)();
Asserts that checked value is greater than or equal to leftBounds.
check(arg, 'arg').is.greaterThanOrEqualTo(0)();
Asserts that checked value is grater than or equal to leftBounds and less than rightBounds.
check(arg, 'arg').is.inRange(0, 100)();
Asserts that checked value a Date chronologically before rightBounds.
check(arg, 'arg').is.before(new Date(0), 'Epoch')();
Asserts that checked value a Date chronologically after leftBounds.
check(arg, 'arg').is.after(new Date(0), 'Epoch')();
Asserts that checked value has field of name propertyName.
check(arg, 'arg').has.property('length')();
Asserts that checked value has field of name propertyName, which satisfied assertion created in gived builder.
check(arg, 'arg').has.propertyThat('x', x => x.is.aNumber)();
Asserts that:
- Checked value is not null or undefined,
- Value of each field of this object satisfies assertuin created by given builder.
check(arg, 'arg').has.allFieldsThat(field => field.is.aNumber)();
Asserts that checked value has field of name methodName which is a function.
check(arg, 'arg').has.method('toString')();
Asserts that checked value has property of name "length" and value of requiredLength.
check(arg, 'arg').has.length(0)();
Asserts that checked value is contained in given set. Given name (if present) is used as a name of set in produced error message.
check(arg, 'arg').is.oneOf([ 'started', 'running', 'finished' ])();
check(arg, 'arg')
.is.oneOf([ 'started', 'running', 'finished' ], 'valid status')
();
Asserts that:
- Checked value is an array of length at least
index
+ 1
, - Element under index satisfies assertion created by given builder.
check(arg, 'arg').has.elementThat(0, elem => elem.is.anInteger)();
Asserts that:
- Checked value is an array,
- Each element of this array satisfies assertuin created by given builder.
check(arg, 'arg').has.allElementsThat(elem => elem.is.anInteger)();
offensive.js implements following operators.
Table of Contents
Logical conjunction of two boolean values which are separated by call to .and
operator.
check(arg, 'arg')
.has.length(2)
.and.allElementsThat(elem => elem.is.aNumber)
();
Logical alternative of two (or more) values which are separated by call to .or
operator.
check(arg, 'arg').is.anObject.or.aFunction();
Logical negation of an assertion after .not
operator.
check(arg, 'arg').is.not.Undefined();
offensive.js is extensible, but extension API is not documented yet.
If you wish to write an extension, take a look at the implementation
of built-in assertions, operators
and also at the interface of Registry
class.
Copyright © 2016 - 2019 Maciej Chałapuk. Released under MIT license.