transformer-chain
Declarative processing of objects with support of filters, default values and validators. It can be used in HTTP API for example.
You may be interested in express middleware (express-request-parameters) for it.
If you need only validation, take a look at validy.

Note: This module works in browsers and Node.js >= 4.0. Use Object.assign
and Promise
polyfills for Internet Explorer
Table of Contents
Demo
Try demo on RunKit.
Installation
npm install transformer-chain
Node.js
const transformer = require('transformer-chain');
Browser
<script src="node_modules/transformer-chain/dist/transformer-chain.js">
or minified version
<script src="node_modules/transformer-chain/dist/transformer-chain.min.js">
You can use the module with AMD/CommonJS or just use window.transformer
.
Overview
transformer-chain
allows you to process flat and nested objects using filters, default values and validators.
There are collections of built-in filters and validators and you can add you own.
Validators can be asynchronous, you can do DB calls for example and so on.
To process object you should define schema. It's simple object with your constraints:
const book = {
name: 'The Adventures of Tom Sawyer',
author: {
name: 'Mark Twain'
},
reviews: [
{
author: 'Leo Tolstoy',
text: 'Great novel',
visible: true
},
{
author: 'Fyodor Dostoyevsky',
text: 'Very interesting'
}
]
};
const schema = {
name: {
$filter: 'trim',
$validate: {
required: true,
string: true
}
},
author: {
$validate: {
required: true
},
name: {
$filter: function(value) {
return typeof value === 'string' ? value.trim() : value;
},
$validate: {
required: true,
string: true
}
}
},
reviews: [{
author: {
$filter: ['trim', ],
$validate: {
required: true,
string: true
}
},
text: {
$filter: [['trim', { }]],
$validate: {
required: true,
string: true
}
},
visible: {
$default: true,
$filter: 'toBoolean'
}
}]
};
const transform = function(object, schema) {
return transformer(object, schema)
.default()
.filter()
.validate()
.project()
.result;
};
transform(book, schema)
.then(result => {
})
.catch(err => {
if (err instanceof transformer.plugins.validate.ValidationError) {
} else {
}
});
async function example() {
try {
const result = transform(book, schema);
} catch(err) {
if (err instanceof transformer.plugins.validate.ValidationError) {
} else {
}
}
}
Usage
transformer(object, schema)
.<plugin1>([options])
.<pluginN>([options])
.result
Parameters
object
(Object) - Object to processschema
(Object) - Schema which defines how to process objectoptions
(Object) - Individual options for plugin
Return value
(Object | Promise) - Result of processing. The module returns promise when at least one of the plugins is asynchronous,
i.e., also returns promise. In all other cases object is returned.
Plugins
By default transformer-chain
comes with four plugins, but you can add your own if it's needed:
const transformer = require('transformer-chain');
transformer.plugins.yourCustomPlugin = function(object, schema) { };
Built-in plugins:
- default
- filter
- validate
- project
You define order in which plugins will be executed by chaining them. Plugins are executed sequentially.
default
Sets default value specified in $default
field to property when its value is undefined
.
filter
$filter
allows you to transform value as you need, format, sanitize, etc.
This plugin comes with collection of filters (common-filters).
validate
This is asynchronous plugin which validates value using set of validators.
It's just wrapper around validy module.
Under the hood validy
uses collection of different validators defined in common-validators module.
project
Unlike other built-in plugins project
plugin does not have special field prefixed by $
.
It allows you to project only those fields that you need. All properties whose config is resolved to object or true
will be presented in result object. It's useful when you want to get some property in result object as is, i.e.,
without any manipulation:
const book = {
name: 'The Adventures of Tom Sawyer',
author: {
name: 'Mark Twain'
}
};
const schema = {
name: {
$filter: 'trim',
$validate: {
required: true,
string: true
}
},
author: true
};
Dynamic schema
Sometimes you may need a way to process some property differently depending on specific conditions.
Example with order of various products:
const order = {
products: [
{
type: 'book',
name: 'The Adventures of Tom Sawyer',
count: 1
},
{
type: 'sugar',
weight: 3000
}
]
};
const productsSchemas = {
book: {
name: {
$validate: {
required: true,
string: true
}
},
count: {
$validate: {
required: true,
integer: true,
min: 1
}
}
},
sugar: {
weight: {
$validate: {
required: true,
integer: true,
min: 1000
}
}
}
};
const schema = {
products: [(product) => {
const productSchema = productsSchemas[product.type];
return Object.assign({}, productSchema, {
type: {
$validate: {
required: true,
string: true,
inclusion: Object.keys(productsSchemas)
}
}
});
}]
};
const alternativeSchema = {
products: {
$validate: {
required: true,
array: true
},
$items: function(product) {
const productSchema = productsSchemas[product.type] || {};
return Object.assign({}, productSchema, {
type: {
$validate: {
required: true,
string: true,
inclusion: Object.keys(productsSchemas)
}
}
});
}
}
};
You can do similar things with $validate
and specific validator:
const bookSchema = {
author: {
name: {
$validate: function(name, author, book, pathToName) {
return {
required: function(name, author, book, pathToName) {
},
string: true
};
}
}
}
};
Don’t repeat yourself
If you have duplicated schemas for different properties you can create collection of common schemas which can be later
reused in multiple places:
const commonSchemas = {
string: function(required = false) {
return {
$filter: 'trim',
validators: {
required: required,
string: true
}
};
},
email: function(required = false) {
return {
$filter: ['trim', 'toLowerCase'],
$validate: {
required: required,
email: true
}
};
}
};
Build
npm install
npm run build
Tests
npm install
npm test
License
MIT