Skip to content

woodger/type-enforcement

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

52 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

Type Enforcement

License Build Status Coverage Status Known Vulnerabilities

Type Enforcement is a js simple and flat library for class-based typing.

Uml diagramm

JavaScript dynamically typed and allows you to declare functions, objects, and variables without declaring a type. Although this feature simplifies the use of the language, it often requires the verification of input data. Type Enforcement helps verify the types of transmitted values on the runtime.

Getting Started

Installation

To use Type Enforcement in your project, run:

npm i type-enforcement

API docs

Table of Contents

class TypeEnforcement

class: TypeEnforcement

Browser-compatible TypeEnforcement class, implemented by following the ECMAScript® 2019 Language Specification standard.

constructor: new TypeEnforcement(shema)

  • shema <Object> An object is an enumeration of rules of the form order : rules <Object>.

In the code there can be more than one validation of the input data, so the rules are grouped into an order.

Except for null and undefined, all primitive values have object equivalents that wrap around the primitive values:

  • String for string primitive.
  • Number for the number of the primitive.
  • Boolean for the boolean primitive.
  • Symbol for Symbol primitive.
  • BigInt for the big number of the primitive.

Therefore, primitives can be declared via an object:

const TypeEnforcement = require('type-enforcement');

const te = new TypeEnforcement({
  primitive: {
    string: String,
    number: Number,
    boolean: Boolean,
    symbol: Symbol
  }
});

NOTE When using a undefined or null, an exception will be thrown.

In addition to primitives, you can use standard built-in objects and custom class, for example:

const TypeEnforcement = require('type-enforcement');

class MyClass {}

const te = new TypeEnforcement({
  inline: {
    object: Object,
    invoke: Function,
    regexp: RegExp,
    array: Array,
    date: Date,
    error: Error,
    promise: Promise
  },
  custom: {
    class: MyClass
  }
});

te.validate(order, values, [options])

  • order <String> scheme name.
  • values <Object> an object is an enumeration of the rules of the form field: value, where field is the name of the value being validate, described in shema.
  • options <Object>
    • skip <Boolean> The skip option allows you to check only part of the values. Default: false.
  • returns: <Error | null>

Unlike the instanceof operator, this method validate if the value of the constructor.prototype rule matches only on the current prototype If all the values of the fields correspond to the scheme, then returns null otherwise returns an error.

const TypeEnforcement = require('type-enforcement');

const te = new TypeEnforcement({
  '#example()': {
    foo: Number,
    bar: Array
  }
});

function example(foo, bar) {
  const err = te.validate('#example()', {
    foo,
    bar
  });

  if (err) {
    throw err;
  }
}

example('1'); // throw Error: Invalid value 'foo' in order '#example()'. Expected Number
example(1); // throw Error: Invalid value 'bar' in order '#example()'. Expected Array
example(1, []); // undefined

The te.validate method is especially useful for implementing default parameters using the capabilities of ECMAScript® 2015 Language Specification standard.

const TypeEnforcement = require('type-enforcement');

const te = new TypeEnforcement({
  '#example()': {
    foo: Number,
    bar: Array
  }
});

function example(foo = 0, bar = []) {
  const err = te.validate('#example()', {
    foo,
    bar
  });

  if (err) {
    throw err;
  }
}

example(); // undefined

This only replaces undefined values with defaults, which is sane. The skip option allows you to check only part of the document, for example:

const TypeEnforcement = require('type-enforcement');

const te = new TypeEnforcement({
  '#example()': {
    foo: Number,
    bar: Array
  }
});

function example(foo, bar) {
  const err = te.validate('#example()', { foo }, { skip: true });
                                          // ↑ 'bar' field is omitted
  if (err) {
    throw err;
  }
}

example('1'); // throw Error: Invalid value 'foo' in order '#example()'. Expected Number
example(1); // undefined

In the example above, the bar field is omitted.

te.normalise(order, values)

  • order <String>
  • values <Object> An object is an enumeration of the rules of the form field: value, where field is the name of the value being validate, described in shema.
  • returns: <Object>

To normalize primitive types, properties of object analogs Primitive(value) are used and a primitive. For other objects, an instance is created with the given value transferred to the constructor.prototype, namely: new Class(value). The following example demonstrates the usefulness of te.normalise(order, values) when using internetwork interoperability of applications.

const values = {
  boo: true,
  now: new Date()
};

const pack = JSON.stringify(values);
// '{"boo":true,"now":"2018-09-26T10:38:08.033Z"}'
//                    ^^^
//                    this is a string type

// ================ interworking ================

const TypeEnforcement = require('type-enforcement');

// Declaring rules
const te = new TypeEnforcement({
  example: {
    boo: Boolean,
    now: Date
  }
});

const json = JSON.parse(pack);
// {boo: true, now: "2018-09-26T10:38:08.033Z"}
//                    ^^^
//                    it's still a string type

const doc = te.normalise('example', json);
// { boo: true, now: 2018-09-26T10:35:41.345Z }
//                    ^^^
//                    this date type

console.log(doc);

The undefined is a property of the global object; i.e., it is a variable in global scope. The initial value of undefined is the primitive value undefined. Note the following example:

Number(undefined); // NaN
Number(); // 0

In the author's opinion, such behavior is useful. The following example will demonstrate this behavior.

const TypeEnforcement = require('type-enforcement');

const te = new TypeEnforcement({
  example: {
    foo: Number,
    bar: String
  }
});

const values = te.normalise(example, {
  foo: undefined,
  bar: undefined
});

console.log(values); // { foo: 0, bar: '' }

About

JavaScript class-based typing

Topics

Resources

License

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published