Skip to content

aeldar/simple-object-transformer

Repository files navigation

Simple Object Transformer

Build Status Build status npm version Coverage Status Dependencies Status NSP Status Greenkeeper badge

NPM

Declare Rules to transform flat JS object into another flat JS object. Useful for simple transformations between internal state objects and server requests/responses.

How to use

Rules is an object with property names equals to the target property name, and the value is one of:

  1. String - then it is considered the property name of the source object, and should be copied into the target as is to specified target property (same as rule's name).
  2. Function - then this function will be applied to the source object and optional property name, and the result will be assigned to the target's property (same as rule's name).
  3. TODO: null|undefined - just copy the value from the same source's property.

The lib exports transformerFactory by default, which allows partial application. I.e. it takes Rules, and returns a Converter, that expects only Source object.

In addition, ordinary transformer could be imported by name. It expects both Rules and Source objects as arguments.

Usage with flowtypes

Import module functions from src directory of the package, instead of a default (which is compiled to ES5 version inside dist directory)

Examples

// const transformerFactory = require('simple-object-transformer').transformerFactory;
import { transformerFactory } from 'simple-object-transformer';

const RULES = Object.freeze({
  id: 'productId',
  name: 'firstName',
  fullName: (context) => `${context.firstName} ${context.lastName}`,
});

const SOURCE = Object.freeze({
  productId: 123,
  firstName: 'John',
  lastName: 'Doe',
  trash: 555,
});

// create a transformer based on the rules, specified as argument
const transformer = transformerFactory(RULES);
const target = transformer(SOURCE);

console.log(target); // { id: 123, name: 'John', fullName: 'John Doe' }

For more examples see tests.

Special notes

To use it as a library you should add "stage-0" preset to your babel configuration, because of object destructuring being used in the code. Also you need babel's transform-flow-strip-types plugin as the code uses flowtype.

TODO

  • implement 'undefined' rule.

Author

Eldar A. eldar.aliyev8@gmail.com

About

Transform flat JS objects according to Rules specified

Resources

License

Stars

Watchers

Forks

Packages