{"id":22503623,"url":"https://github.com/jokero/transformer-chain","last_synced_at":"2025-03-27T23:14:47.494Z","repository":{"id":57379071,"uuid":"41411188","full_name":"Jokero/transformer-chain","owner":"Jokero","description":"Declarative processing of objects with support of filters, default values and validators","archived":false,"fork":false,"pushed_at":"2018-08-27T11:58:32.000Z","size":93,"stargazers_count":3,"open_issues_count":1,"forks_count":0,"subscribers_count":3,"default_branch":"master","last_synced_at":"2025-03-02T22:45:55.490Z","etag":null,"topics":["asynchronous","declarative","defaults","filter","validation"],"latest_commit_sha":null,"homepage":"","language":"JavaScript","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/Jokero.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null}},"created_at":"2015-08-26T07:29:31.000Z","updated_at":"2018-08-27T11:58:35.000Z","dependencies_parsed_at":"2022-09-02T20:41:21.267Z","dependency_job_id":null,"html_url":"https://github.com/Jokero/transformer-chain","commit_stats":null,"previous_names":[],"tags_count":5,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/Jokero%2Ftransformer-chain","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/Jokero%2Ftransformer-chain/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/Jokero%2Ftransformer-chain/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/Jokero%2Ftransformer-chain/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/Jokero","download_url":"https://codeload.github.com/Jokero/transformer-chain/tar.gz/refs/heads/master","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":245938228,"owners_count":20697008,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["asynchronous","declarative","defaults","filter","validation"],"created_at":"2024-12-06T23:37:16.066Z","updated_at":"2025-03-27T23:14:47.475Z","avatar_url":"https://github.com/Jokero.png","language":"JavaScript","funding_links":[],"categories":[],"sub_categories":[],"readme":"# transformer-chain\n\nDeclarative processing of objects with support of filters, default values and validators. It can be used in HTTP API for example.\nYou may be interested in express middleware ([express-request-parameters](https://github.com/Jokero/express-request-parameters)) for it.\nIf you need only validation, take a look at [validy](https://github.com/Jokero/validy).\n\n[![NPM version](https://img.shields.io/npm/v/transformer-chain.svg)](https://npmjs.org/package/transformer-chain)\n[![Build status](https://img.shields.io/travis/Jokero/transformer-chain.svg)](https://travis-ci.org/Jokero/transformer-chain)\n\n**Note:** This module works in browsers and Node.js \u003e= 4.0. Use `Object.assign` and `Promise` polyfills for Internet Explorer\n\n## Table of Contents\n\n- [Demo](#demo)\n- [Installation](#installation)\n  - [Node.js](#nodejs)\n  - [Browser](#browser)\n- [Overview](#overview)\n- [Usage](#usage)\n  - [Parameters](#parameters)\n  - [Return value](#return-value)\n- [Plugins](#plugins)\n  - [default](#default)\n  - [filter](#filter)\n  - [validate](#validate)\n  - [project](#project)\n- [Dynamic schema](#dynamic-schema)\n- [Don’t repeat yourself](#dont-repeat-yourself)\n- [Build](#build)\n- [Tests](#tests)\n- [License](#license)\n\n## Demo\n\nTry [demo](https://runkit.com/npm/transformer-chain) on RunKit.\n\n## Installation\n\n```sh\nnpm install transformer-chain\n```\n\n### Node.js\n```js\nconst transformer = require('transformer-chain');\n```\n\n### Browser\n```\n\u003cscript src=\"node_modules/transformer-chain/dist/transformer-chain.js\"\u003e\n```\nor minified version\n```\n\u003cscript src=\"node_modules/transformer-chain/dist/transformer-chain.min.js\"\u003e\n```\n\nYou can use the module with AMD/CommonJS or just use `window.transformer`.\n\n## Overview\n\n`transformer-chain` allows you to process flat and nested objects using filters, default values and validators.\nThere are collections of built-in filters and validators and you can add you own. \nValidators can be asynchronous, you can do DB calls for example and so on.\n\nTo process object you should define schema. It's simple object with your constraints:\n\n```js\nconst book = { // object to process\n    name: 'The Adventures of Tom Sawyer',\n    author: {\n        name: 'Mark Twain'\n    },\n    reviews: [\n        {\n            author: 'Leo Tolstoy',\n            text: 'Great novel',\n            visible: true\n        },\n        {\n            author: 'Fyodor Dostoyevsky',\n            text: 'Very interesting'\n        }\n    ]\n};\n\nconst schema = {\n    name: {\n        $filter: 'trim',\n        $validate: {\n            required: true,\n            string: true\n        }\n    },\n    author: {\n        $validate: { // you can omit check that \"author\" value is object, it will be done internally \n            required: true\n        },\n    \n        name: {\n            $filter: function(value) { // you can use function for filtration\n                // this example has the same behaviour as built-in \"trim\": it trims only strings\n                return typeof value === 'string' ? value.trim() : value;\n            },\n            $validate: {\n                required: true,\n                string: true\n            }\n        }\n    },\n    reviews: [{ // define schema for array items\n        author: {\n            $filter: ['trim', /* another filter */], // you can use array of filters\n            $validate: {\n                required: true,\n                string: true\n            }\n        },\n        text: {\n            $filter: [['trim', { /* some options */ }]], // you can pass additional options to filter if needed\n            $validate: {\n                required: true,\n                string: true\n            }\n        },\n        visible: {\n            $default: true, // default value will be set when actual value of property is undefined\n            $filter: 'toBoolean' // always returns boolean\n        }\n    }]\n};\n\nconst transform = function(object, schema) {\n    // you can run plugins in the order you want, but this one looks reasonable\n    return transformer(object, schema)\n        .default()\n        .filter()\n        .validate()\n        .project()\n        .result;\n}; \n\ntransform(book, schema)\n    .then(result =\u003e {\n        // result is transformed object\n    })\n    .catch(err =\u003e {\n        if (err instanceof transformer.plugins.validate.ValidationError) {\n            // you have validation errors\n        } else {\n            // application error (something went wrong)\n        }\n    });\n\n// async/await example\nasync function example() {\n    try {\n        const result = transform(book, schema);\n    } catch(err) {\n        if (err instanceof transformer.plugins.validate.ValidationError) {\n            // you have validation errors\n        } else {\n            // application error (something went wrong)\n        }\n    }\n}\n```\n\n## Usage\n\n```\ntransformer(object, schema)\n    .\u003cplugin1\u003e([options])\n    .\u003cpluginN\u003e([options])\n    .result\n```\n\n#### Parameters\n\n- `object` (Object) - Object to process\n- `schema` (Object) - Schema which defines how to process object\n- `options` (Object) - Individual options for plugin\n\n#### Return value\n\n(Object | Promise) - Result of processing. The module returns promise when at least one of the plugins is asynchronous, \ni.e., also returns promise. In all other cases object is returned.\n\n### Plugins\n\nBy default `transformer-chain` comes with four plugins, but you can add your own if it's needed:\n\n```js\nconst transformer = require('transformer-chain');\ntransformer.plugins.yourCustomPlugin = function(object, schema) { /* plugin implementation */ };\n```\n\nBuilt-in plugins:\n\n- default\n- filter\n- validate\n- project\n\nYou define order in which plugins will be executed by chaining them. Plugins are executed sequentially.\n\n#### default\n\nSets default value specified in `$default` field to property when its value is `undefined`.\n\n#### filter\n\n`$filter` allows you to transform value as you need, format, sanitize, etc.\nThis plugin comes with collection of filters ([common-filters](https://github.com/tamtakoe/common-filters)).\n\n#### validate\n\nThis is asynchronous plugin which validates value using set of validators. \nIt's just wrapper around [validy](https://github.com/Jokero/validy) module. \nUnder the hood `validy` uses collection of different validators defined in [common-validators](https://github.com/tamtakoe/common-validators) module.\n\n#### project\n\nUnlike other built-in plugins `project` plugin does not have special field prefixed by `$`.\nIt allows you to project only those fields that you need. All properties whose config is resolved to object or `true` \nwill be presented in result object. It's useful when you want to get some property in result object as is, i.e., \nwithout any manipulation:\n\n```js\nconst book = {\n    name: 'The Adventures of Tom Sawyer',\n    author: {\n        name: 'Mark Twain'\n    }\n};\n\nconst schema = {\n    name: {\n        $filter: 'trim',\n        $validate: {\n            required: true,\n            string: true\n        }\n    },\n    author: true // here we say that we need this field in result object without any changes\n};\n```\n\n### Dynamic schema\n\nSometimes you may need a way to process some property differently depending on specific conditions.\nExample with order of various products:\n\n```js\nconst order = {\n    products: [\n        {\n            type: 'book',\n            name: 'The Adventures of Tom Sawyer',\n            count: 1\n        },\n        {\n            type: 'sugar',\n            weight: 3000\n        }\n    ]\n};\n\nconst productsSchemas = {\n    book: {\n        name: {\n            $validate: {\n                required: true,\n                string: true\n            }\n        },\n        count: {\n            $validate: {\n                required: true,\n                integer: true,\n                min: 1\n            }\n        }\n    },\n\n    sugar: {\n        weight: {\n            $validate: {\n                required: true,\n                integer: true,\n                min: 1000\n            }\n        }\n    }\n};\n\nconst schema = {\n    products: [(product/*, products, order, pathToItem*/) =\u003e {\n        const productSchema = productsSchemas[product.type];\n        return Object.assign({}, productSchema, {\n            type: {\n                $validate: {\n                    required: true,\n                    string: true,\n                    inclusion: Object.keys(productsSchemas)\n                }\n            }\n        });\n    }]\n};\n\n// or you can do like this\n\nconst alternativeSchema = {\n    products: {\n        $validate: { // validate also \"products\" before items validation\n            required: true,\n            array: true\n        },\n\n        $items: function(product/*, products, order, pathToItem*/) {\n            const productSchema = productsSchemas[product.type] || {};\n            return Object.assign({}, productSchema, {\n                type: {\n                    $validate: {\n                        required: true,\n                        string: true,\n                        inclusion: Object.keys(productsSchemas)\n                    }\n                }\n            });\n        }\n    }\n};\n```\n\nYou can do similar things with `$validate` and specific validator:\n\n```js\nconst bookSchema = {\n    author: {\n        name: {\n            $validate: function(name, author, book, pathToName) {\n                // implement your custom logic\n                \n                // validation will only run if you return object\n                // so you can return null for example to skip validation \n                return {\n                    required: function(name, author, book, pathToName) {\n                        // implement your custom logic\n                        // return undefined, null or false if you want skip validation\n                    },\n                    string: true\n                };\n            }\n        }\n    }\n};\n```\n\n### Don’t repeat yourself\n\nIf you have duplicated schemas for different properties you can create collection of common schemas which can be later\nreused in multiple places:\n\n```js\nconst commonSchemas = {\n    string: function(required = false) {\n        return {\n            $filter: 'trim',\n            validators: {\n                required: required,\n                string: true\n            }\n        };\n    },\n    \n    email: function(required = false) {\n        return {\n            $filter: ['trim', 'toLowerCase'],\n            $validate: {\n                required: required,\n                email: true\n            }\n        };\n    }\n};\n```\n\n## Build\n\n```sh\nnpm install\nnpm run build\n```\n\n## Tests\n\n```sh\nnpm install\nnpm test\n```\n\n## License\n\n[MIT](LICENSE)\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fjokero%2Ftransformer-chain","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fjokero%2Ftransformer-chain","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fjokero%2Ftransformer-chain/lists"}