@yrnd1/

Morphism Full Example

ES6

No description

fork
loading

This Plugin Crashed!

Error: Error: must not create an existing file {"type":"CREATE_FILE","wid":"0.20761783239289167","path":"main.js","file":{"path":"main.js","content":{"asEncoding":{"base64":"aW1wb3J0IHsgbW9ycGhpc20gfSBmcm9tICJtb3JwaGlzbSI7CgovLyBTb3VyY2UgZGF0YSBjb21pbmcgZnJvbSBhbiBBUEkuCmNvbnN0IHNvdXJjZSA9IHsKICBmb286ICJiYXoiLAogIGJhcjogWyJiYXIiLCAiZm9vIl0sCiAgYmF6OiB7CiAgICBxdXg6ICJiYXpxdXgiCiAgfQp9OwoKLy8gVGFyZ2V0IENsYXNzIGluIHdoaWNoIHRvIG1vcnBoIHRoZSBzb3VyY2UgZGF0YS4KY2xhc3MgRGVzdGluYXRpb24gewogIGZvbyA9IG51bGw7CiAgYmFyID0gbnVsbDsKICBiYXpxdXggPSBudWxsOwp9CgovLyBBIHN0cnVjdHVyZS1wcmVzZXJ2aW5nIG9iamVjdCBmcm9tIGEgc291cmNlIGRhdGEgdG93YXJkcyBhIHRhcmdldCBkYXRhLgpjb25zdCBzY2hlbWEgPSB7CiAgZm9vOiAiYmFyWzFdIiwgLy8gR3JhYiB0aGUgcHJvcGVydHkgdmFsdWUgYnkgaGlzIHBhdGgKICBiYXI6IChpdGVyYXRlZSwgc291cmNlLCBkZXN0aW5hdGlvbikgPT4gewogICAgLy8gQXBwbHkgYSBGdW5jdGlvbiBvbiB0aGUgY3VycmVudCBlbGVtZW50CiAgICByZXR1cm4gaXRlcmF0ZWUuYmFyWzBdOwogIH0sCiAgYmF6cXV4OiB7CiAgICAvLyBBcHBseSBhIGZ1bmN0aW9uIG9uIHByb3BlcnR5IHZhbHVlCiAgICBwYXRoOiAiYmF6LnF1eCIsCiAgICBmbjogKHByb3BlcnR5VmFsdWUsIHNvdXJjZSkgPT4gewogICAgICByZXR1cm4gcHJvcGVydHlWYWx1ZTsKICAgIH0KICB9Cn07Cgpjb25zdCBjbGFzc09iamVjdHMgPSBtb3JwaGlzbShzY2hlbWEsIHNvdXJjZSwgRGVzdGluYXRpb24pOwovLyBEZXN0aW5hdGlvbiB7Zm9vOiAiZm9vIiwgYmFyOiAiYmFyIiwgYmF6cXV4OiAiYmF6cXV4In0KCmNvbnN0IGpzT2JqZWN0cyA9IG1vcnBoaXNtKHNjaGVtYSwgc291cmNlKTsKLy8gT2JqZWN0IHtmb286ICJmb28iLCBiYXI6ICJiYXIiLCBiYXpxdXg6ICJiYXpxdXgifQpjb25zb2xlLmxvZyhjbGFzc09iamVjdHMpOwpjb25zb2xlLmxvZyhqc09iamVjdHMpOwo="},"asBuffer":null},"loaded":true}}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
import { morphism } from "morphism";

// Source data coming from an API.
const source = {
  foo: "baz",
  bar: ["bar", "foo"],
  baz: {
    qux: "bazqux"
  }
};

// Target Class in which to morph the source data.
class Destination {
  foo = null;
  bar = null;
  bazqux = null;
}

// A structure-preserving object from a source data towards a target data.
const schema = {
  foo: "bar[1]", // Grab the property value by his path
  bar: (iteratee, source, destination) => {
    // Apply a Function on the current element
    return iteratee.bar[0];
  },
  bazqux: {
    // Apply a function on property value
    path: "baz.qux",
    fn: (propertyValue, source) => {
      return propertyValue;
    }
  }
};

const classObjects = morphism(schema, source, Destination);
// Destination {foo: "foo", bar: "bar", bazqux: "bazqux"}

const jsObjects = morphism(schema, source);
// Object {foo: "foo", bar: "bar", bazqux: "bazqux"}
console.log(classObjects);
console.log(jsObjects);
Babel Compiler v6.4.4 Copyright (c) 2014-2015 Sebastian McKenzie