1 Star 0 Fork 0

emyann / morphism

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
克隆/下载
贡献代码
同步代码
取消
提示: 由于 Git 不支持空文件夾,创建文件夹后会生成空的 .keep 文件
Loading...
README
MIT

Morphism

NPM version Build Status Dependency Status Coverage percentage

Helps you to transform any object structure to another

Contribution

Getting started 🚀

Install morphism using npm.

npm install --save morphism

Then require it into any module.

const Morphism = require('morphism'); 

Or using ES6 import style

import Morphism from 'morphism';

If you're using browserify, the morphism npm module also works from the browser.

What does it do? 🤔

Morphism uses a semantic configuration to go through the collection of graph objects you have to process. Then it extracts and computes the value from the specified path(s). Finally, it sets this value to the destination property from the schema.

Usage 🍔

Morphism is curried function that allows a partial application with a semantic configuration. You can use it in many ways:

Along with an ES6 Class

// Target type you want to have
class User {
    constructor(firstName, lastName, phoneNumber){
        this.firstName = firstName;
        this.lastName = lastName;
        this.phoneNumber = phoneNumber;
        this.city = null;
   }
}

// Data source you want to map
let data = [{
                'firstName': 'John',
                'lastName': 'Smith',
                'address':
                    {
                        'city': 'New York',
                        'country': 'USA'
                    },
                'phoneNumber':
                    [
                        {
                            'type': 'home',
                            'number': '212 555-1234'
                        },
                        {
                            'type': 'fax',
                            'number': '646 555-4567'
                        }
                    ]
             }];
// Mapping Schema ( see more examples below )
let schema = {
    city: 'adress.city',
    phoneNumber: (object) => object.phoneNumber.filter(c => c.type === 'home')[0].number;
}

let mapUser = Morphism.register(User, schema);

// Map using the registered type and the registry
Morphism.map(User, data)

// Or Map using the mapper reference
mapUser(data);

/// *** OUTPUT *** ///

[{
    'firstName': 'John',
    'lastName': 'Smith',
    'phoneNumber': '212 555-1234',
    'city': 'New York'
 }]

As a Mapper factory


let mapping = { ... }
let collectionOfObjects = [ ... ]
let anotherCollection = [ ... ]

// produces a reusable mapper from the configuration
let myAwesomeMapper = Morphism(mapping);
myAwesomeMapper(collectionOfObjects);
myAwesomeMapper(anotherCollection);

As a Static instance

const Morphism = require('morphism'); 

let mapping = { ... }
let collectionOfObjects = [ ... ]

// extracts the data straight away 
let results = Morphism(mapping, collectionOfObjects);

Mapping Schema Examples 💡

Dataset sample

// We'll use this set of data all along the examples
let data = [{
                'firstName': 'John',
                'lastName': 'Smith',
                'address':
                {
                    'city': 'New York',
                    'country': 'USA'
                },
                'phoneNumber':
                    [
                        {
                            'type': 'home',
                            'number': '212 555-1234'
                        },
                        {
                            'type': 'fax',
                            'number': '646 555-4567'
                        }
                    ]
                }];

Flattening and Projection

let data = [ ... ];
let mapping = { 
                pseudo: 'firstName', // Simple Projection
                lastName: 'lastName',
                city: 'address.city' // Flatten a value from a deep path
               };

let results = Morphism(mapping, data);

// results[0]: {
//                 pseudo: 'John',
//                 lastName: 'Smith',
//                 city: 'New York'
//             }

Computing over Flattening / Projection

let data = [ ... ];
let mapping = { 
                pseudo: 'firstName',
                lastName: 'lastName',
                city: {
                    path: 'address.city',
                    fn: (city) => city.toLowerCase() // compute a function on the specified path value
                },
                nbContacts: (object) => object.phoneNumber.length // compute a function on the iteratee object

               };

let mapper = Morphism(mapping);
let results = mapper(data);

// results[0]): {
//                 pseudo: 'John',
//                 lastName: 'Smith',
//                 city: 'new york',// <== toLowerCase
//                 nbContacts: 2 // <== computed from the object
//              }

Values Aggregation

let data = [ ... ];

let mapping = {
                user: ['firstName','lastName'] // aggregate the values to an object
                city: 'address.city'
               };

let results = Morphism(mapping, data);

// results[0]: {
//                 user: {
//                     'firstName': 'John',
//                     'lastName': 'Smith'
//                 },
//                 city: 'New York'
//             }

Mappers Registry 📚

Morphism provides a powerful local registry where you can store your mappings' configuration by specifying a Class Type. The transformation sequences are stored as a function in a WeakMap to speed the processing.

Register a mapping configuration along with a Class

class User {
    constructor(firstName, lastName, phoneNumber){
        this.firstName = firstName;
        this.lastName = lastName;
        this.phoneNumber = phoneNumber;
    }
}

let mapUser = Morphism.register(User, schema);

// Map using the registered type and the registry
Morphism.map(User, data)

// Or Map using the mapper reference
mapUser(data);

API 📚

Register

Register a mapper for a specific type. The schema is optional.

Morphism.register(type, schema:{});

Map

Map a collection of objects to the specified type

Morphism.map(type, data:[]);

Get or Set an existing mapper configuration

Morphism.setMapper(type, schema:{});

Delete a registered mapper

Morphism.deleteMapper(type, schema:{});

License

MIT © Yann Renaudin

The MIT License (MIT) Copyright (c) 2016 Yann Renaudin <renaudin.yann@gmail.com> Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

简介

Transform any Object / JSON to JavaScript Object Literals, and ES6 Class Objects. Scale your data processing. 展开 收起
JavaScript
MIT
取消

发行版

暂无发行版

贡献者

全部

近期动态

加载更多
不能加载更多了
JavaScript
1
https://gitee.com/emyann/morphism.git
git@gitee.com:emyann/morphism.git
emyann
morphism
morphism
master

搜索帮助