fully-typed
Run time type validation, transformation, and error generator that works out of the box on primitives, objects, arrays, and nested objects. Also extensible for custom types.
Skip to Table of Contents
Features
- Create schemas to validate values against.
- Built in support for arrays, booleans, functions, numbers, objects, strings, and symbols.
- Extensible - use plugins or create your own to integrate more types.
- Get detailed error messages when a wrong value is run against a schema.
- Auto throw errors when normalizing or validating.
Example
const Typed = require('fully-typed');
const schema = Typed({
type: Number,
default: 0
});
exports.add = function (a, b) {
a = schema.normalize(a);
b = schema.normalize(b);
return a + b;
};
Example
const Typed = require('fully-typed');
const schema = Typed({
type: Object,
properties: {
name: {
required: true,
type: String,
minLength: 1
},
age: {
type: Number,
min: 0
},
employed: {
type: Boolean,
default: true
}
}
});
function addPerson(configuration) {
const config = schema.normalize(configuration);
}
Example
const Typed = require('fully-typed');
const positiveIntegerSchema = Typed({
type: Number,
default: 100,
min: 0,
integer: true
});
const value = positiveIntegerSchema.normalize(undefined);
positiveIntegerSchema.error(0);
positiveIntegerSchema.error(1);
positiveIntegerSchema.error(-1);
positiveIntegerSchema.error(1.2);
positiveIntegerSchema.error('1');
positiveIntegerSchema.validate(-1);
positiveIntegerSchema.normalize(-1);
Table of Contents
Schema Configurations
Shared Configuration Options
All types defined share the following common configuration options:
-
default - A value to use during normalization if the value is undefined
. This is especially useful for the properties of object configurations.
const schema = Typed({
default: 'Hello, World!'
});
const value1 = schema.normalize('Hello, Bob!');
const value2 = schema.normalize();
-
enum - (Array) A non-empty array of acceptable values. Values are compared using triple equals ===
.
const schema = Typed({
enum: ['A', 2, null]
});
schema.error('A');
schema.error(2);
schema.error(null);
schema.error('a');
schema.error(1);
schema.error({});
-
transform - (Function) This function is only run during normalization. It receives the validated value and must return a value. The value returned will be the result of normalization.
const schema = Typed({
transform: function(value) {
return !!value;
}
});
-
validator - (Function) This function provides an easy method for adding some custom validation to a schema. The validator will be passed the value as its only parameter. Returning a truthy value means the value is valid, returning a string or a falsy value signifies an invalid value. If a string is returned then the value for the string is placed in the error message.
const schema = Typed({
validator: function(value) {
const num = Math.random();
return value === num
? true
: 'The only acceptable value is ' + num;
}
});
Back to Table of Contents
Array
An array type will require the input to be an array.
Type Aliases: 'array'
, Array
In addition to the shared configuration options it also has these options:
-
maxItems - (Number) The maximum number of items that the array can contain. Defaults to undefined
.
-
minItems - (Number) The minimum number of items that the array must contain. Defaults to 0
.
-
schema - (Object) A configuration schema to apply to each item in the array. For example, you can specify that the array must be an array of numbers.
const schema = Typed({
type: Array,
schema: {
type: Number
}
});
-
uniqueItems - (Boolean) If set to true then each item in the array must be unique. Defaults to false
.
const schema = Typed({
type: Array,
uniqueItems: true
});
schema.error([1, 'b']);
schema.error([1, 1]);
Back to Table of Contents
Boolean
An boolean type will accept any value and transform it into a boolean unless the strict
option is set. Under strict
this type will only accept a boolean.
Type Aliases: 'boolean'
, Boolean
In addition to the shared configuration options it also has this option:
-
strict - (Boolean) Set to true to require that the type be a boolean. Defaults to false
.
const loose = Typed({
type: Boolean
});
const strict = Typed({
type: Boolean,
strict: true
});
loose.error(1);
strict.error(1);
strict.error(true);
const value = loose.normalize(1);
Back to Table of Contents
Date
A date type will require that the input be a valid Date or that it be a value that can be converted to a valid Date.
Type Aliases: 'date'
, Date
In addition to the shared configuration options it also has these options:
-
max - (Date, string, number) The maximum allowed date value. Defaults to undefined
.
const schema = Typed({
type: Date,
max: '2017-01-01'
});
schema.error(new Date('2015-01-01'));
schema.error(new Date('2017-02-01'));
-
min - (Date, string, number) The minimum allowed date value. Defaults to undefined
.
const schema = Typed({
type: Date,
min: '2017-01-01'
});
schema.error(new Date('2017-02-01'));
schema.error(new Date('2015-01-01'));
Back to Table of Contents
Function
An function type will require the input to be a function.
Type Aliases: 'function'
, Function
In addition to the shared configuration options it also has these options:
-
maxArguments - (Number) The maximum number of arguments that the function can define as parameters. Defaults to undefined
.
const schema = Typed({
type: Function,
maxArguments: 0
});
schema.error(function() {});
schema.error(function(a) {});
-
minArguments - (Number) The minimum number of arguments that the function can define as parameters. Defaults to 0
.
const schema = Typed({
type: Function,
minArguments: 3
});
schema.error(function(a, b, c) {});
schema.error(function() {});
-
named - (Boolean) Require the function to be named. Defaults to false
.
const schema = Typed({
type: Function,
named: true
});
schema.error(function foo() {});
schema.error(function() {});
Back to Table of Contents
Number
An number type will require the input to be a number.
Type Aliases: 'number'
, Number
In addition to the shared configuration options it also has these options:
-
exclusiveMax - (Boolean) Whether the maximum value should be included as allowed or not. Defaults to false
.
const schema = Typed({
type: Number,
exclusiveMax: true,
max: 1
});
schema.error(.999);
schema.error(1);
-
exclusiveMin - (Boolean) Whether the minimum value should be included as allowed or not. Defaults to false
.
const schema = Typed({
type: Number,
exclusiveMin: true,
min: 1
});
schema.error(1.001);
schema.error(1);
-
integer - (Boolean) Whether the value must be an integer. Defaults to false
.
const schema = Typed({
type: Number,
integer: true
});
schema.error(1);
schema.error(1.2);
-
max - (Number) The maximum allow value. Defaults to undefined
.
const schema = Typed({
type: Number,
max: 1
});
schema.error(-1);
schema.error(1);
schema.error(2);
-
min - (Number) The minimum allow value. Defaults to undefined
.
const schema = Typed({
type: Number,
min: 1
});
schema.error(-1);
schema.error(1);
schema.error(2);
Back to Table of Contents
Object
An object type will require the input to be an object. You can also specify which properties are required and the schema expected for individual properties.
Normalization of this type produces a new object.
Type Aliases: 'object'
, Object
In addition to the shared configuration options it also has these options:
-
allowNull - (Boolean) Whether null
is an acceptable value. Defaults to true
.
const nullSchema = Typed({
type: Object,
allowNull: true
});
const notNullSchema = Typed({
type: Object
});
nullSchema.error({});
nullSchema.error(null);
notNullSchema.error({});
notNullSchema.error(null);
-
clean - (Boolean) During normalization remove any properties that are not defined in the schema's properties. Defaults to false
.
const schema = Typed({
type: Object,
clean: true,
properties: {
name: {
type: String,
minLength: 1,
required: true
},
age: {
type: Number,
min: 0,
integer: true
}
}
});
const value = schema.normalize({
name: 'Bob',
age: 5,
location: 'Utah'
});
-
properties - (Object) Define the properties that can be part of this object. Each property takes a full schema configuration. Each property is also given a required
property that can be set to true.
const schema = Typed({
type: Object,
properties: {
name: {
type: String,
minLength: 1,
required: true
},
age: {
type: Number,
min: 0,
integer: true
}
}
});
schema.error({ name: 'Bob' });
schema.error({});
-
schema - (Object) A configuration schema to apply to each property on the object. This is useful for allowing objects to have any property but requiring that each property adhere to a schema. If specific properties are defined then the schema defined here will be extended by and superseded by the specific property's schema.
const schema = Typed({
type: Object,
properties: {
name: {
minLength: 1,
required: true
},
age: {
type: Number
}
},
schema: {
type: String,
minLength: 10
}
});
schema.error({ name: 'Bob' });
schema.error({});
The following example shows a one-of general schema definition. All variations of the general schema are possible extensions across the property specific schemas.
const schema = Typed({
type: Object,
properties: {
name: {
type: String,
minLength: 1
},
age: {
type: Number
},
foo: {
min: 5,
minLength: 1,
required: true
}
},
schema: [
{
type: String,
maxLength: 10
},
{
type: Number,
min: 0,
max: 10
},
{
type: Number,
min: 20,
max: 30
}
]
});
schema.error({ name: 'Bob' });
schema.error({});
Back to Table of Contents
One-Of
It is possible to allow multiple variations of schemas. For example, you may want to allow numbers and strings.
const schema = Typed({
type: Typed.OneOf,
oneOf: [
{
type: Number,
min: 0
},
{
type: String
}
]
});
schema.error('Foo');
schema.error(1);
schema.error(-1);
schema.error(true);
Back to Table of Contents
String
A string type will require the input to be a string.
Type Aliases: 'string'
, String
In addition to the shared configuration options it also has these options:
-
maxLength - (Number) The maximum length to allow for the string. Defaults to undefined
.
const schema = Typed({
type: String,
maxLength: 3
});
schema.error('foo');
schema.error('food');
-
minLength - (Number) The minimum length to allow for the string. Defaults to 0
.
const schema = Typed({
type: String,
minLength: 1
});
schema.error('a');
schema.error('');
-
pattern - (RegExp) A regular expression object to test against the string. Defaults to undefined
.
const schema = Typed({
type: String,
pattern: /^[a-z]$/i
});
schema.error('a');
schema.error('1');
Back to Table of Contents
Symbol
A symbol type will require the input to be a symbol.
Type Aliases: 'symbol'
, Symbol
This type inherits the shared configuration options and has no options of its own.
Back to Table of Contents
Schema Instance
A schema is generated by passing a schema configuration into the Typed function:
const Typed = require('fully-typed');
const schema = Typed({
type: Number
})
Once a schema is created you can check a value for errors, normalize a value, or validate a value.
Back to Table of Contents
config
Get a copy of the configuration that was used to define the schema for the current instance.
const schema = Typed({
type: Object,
allowNull: false
})
const config = schema.config;
error
Test a value for errors. If the value does produce an error then a string is returned that details the cause of the error.
Parameters
Returns null
if no errors otherwise a string with error details.
const schema = Typed({
type: Number
});
schema.error(1);
schema.error('a');
Back to Table of Contents
normalize
Validate a value and if an error is not thrown then begin normalization. Normalization differs for different types, but the essential role is to get the value into a state where you are ready to work with it. For example, booleans are normalized to true
or false
from truthy or falsy values respectively.
Parameters
- value - The value to normalize.
Returns The new value.
const schema = Typed({
type: Boolean
});
const value1 = schema.normalize(1);
const value2 = schema.normalize(null);
Back to Table of Contents
validate
The validate function checks for errors and if there is one it throws an error.
Parameters
Returns undefined.
const schema = Typed({
type: Number
});
schema.validate(1);
schema.validate('a');
Back to Table of Contents
Plugins
The fully typed library can be extended with new types.
Use an Existing Plugin
-
Find an Existing Plugin
-
Require the plugin in your project along with fully-typed
.
-
Register the plugin with fully-typed
.
const FullyTyped = require('fully-typed');
const plugin = require('some-full-typed-plugin');
FullyTyped.controllers.register(plugin);
-
Now you can create schema's that use that plugin's type and associated configurations.
Back to Table of Contents
Write a Plugin
A plugin is created by defining a typed controller. See the example.
-
Define a constructor function that accepts a configuration as it's only parameter.
function MyController (config) { }
-
Define and validate the configuration properties that are important to your controller.
-
Define the controller's properties. These are often similar or derived from the configuration properties.
-
Optionally define the error generator function on the prototype of the controller. This function will be used for normalization and validation.
MyController.prototype.error = function (value, prefix) { }
This function will receive two parameters when called: 1) the value to validate, 2) a prefix to add to the beginning of any returned error messages.
This function should return a string with an error message if an invalid value is passed in, otherwise it should return null
.
-
Optionally define the normalize function. This function will be called after passing validation and can make any transformations to the value.
MyController.prototype.normalize = function (value) { }
This function receives the value parameter. It must return the normalized value.
-
Provide the registration directive. This tells full-typed
what aliases to assign to your controller and what dependencies this controller has. All controllers will automatically inherit from the Typed core controller.
MyController.register = {
aliases: ['my-controller'],
dependencies: []
}
The alias can be any value (primitive or object) but each alias must be unique within the entire system of typed controllers. The dependencies can reference the typed controllers by any alias they are registered with.
-
Register your controller.
Back to Table of Contents
TypedDate Controller Example
This is one of the built in controllers, but here it is documented to help you create your own controllers / plugins.
module.exports = TypedDate;
function TypedDate (config) {
const max = toDate(config.max);
const min = toDate(config.min);
if (config.hasOwnProperty('max') && !max) {
throw Error('Property max could not be converted to a valid date. Received: ' + config.max);
}
if (config.hasOwnProperty('min') && !min) {
throw Error('Property min could not be converted to a valid date. Received: ' + config.min);
}
if (max !== undefined && min !== undefined && min > max) {
throw Error('The max date value must be greater than or equal to the min date value.');
}
Object.defineProperties(this, {
max: {
value: max
},
min: {
value: min
}
});
}
TypedDate.prototype.error = function(value, prefix) {
const d = toDate(value);
if (!d) return prefix + 'Value cannot be converted to a valid date: ' + value;
if (this.max && d > this.max) return prefix + 'Value must be less than or equal to the max date value.';
if (this.min && d < this.min) return prefix + 'Value must be greater than or equal to the min date value.';
return null;
};
TypedDate.prototype.normalize = function(value) {
return toDate(value);
};
TypedDate.register = {
aliases: ['date', Date],
dependencies: []
};
function toDate(value) {
const d = value instanceof Date
? value
: new Date(value);
return isNaN(+d) ? undefined : d;
}
Finally, we need to register the controller:
const FullyTyped = require('fully-typed');
FullyTyped.controllers.register(TypedDate);
Back to Table of Contents
Controller API
Register
Register a controller with the typed system to enable use of the type. You will need this function if you are including types from other libraries or if you are writing your own typed controller.
Parameters
- controller - A valid controller function as defined in the Write a Plugin section.
Returns undefined.
Typed.controllers.register ( controller );
Back to Table of Contents
Delete
Delete an existing controller.
Parameters
- alias - An alias of the controller you want to delete.
Returns undefined.
Typed.controllers.delete ('alias');
Back to Table of Contents
Get
Get an existing controllers data structure.
Parameters
- alias - An alias of the controller you want to get.
Returns null if not found, or an object with the following format:
-
alias - The primary alias name.
-
aliases - An array of all aliases.
-
controller - The primary controller function.
-
controllers - An array of all controllers (including dependency controllers) that make up the controller.
-
errorFunctions - An array of all error functions (including dependency error functions).
-
dependencies - Aliases for all dependencies for this controller.
-
normalizeFunctions - An array of all normalize functions (including dependency error functions).
const data = Typed.controllers.get ('alias');
Back to Table of Contents
Has
Check to see if a controller has been defined with the specified alias.
Parameters
- alias - An alias of the controller you check for.
Returns true
if registered, false
if not registered.
Typed.controllers.has ('alias');
Back to Table of Contents
Is
Check to see if two aliases are referencing the same controller.
Parameters
Returns true
if both aliases are for the same controller, otherwise false
.
Typed.controllers.is ('alias1', 'alias2');
Back to Table of Contents
List
Get an array of all registered type controllers.
Parameters None
Returns an array of controller data objects.
Typed.controllers.list ();
Back to Table of Contents