Skip to content
This repository has been archived by the owner on Jan 20, 2024. It is now read-only.

Commit

Permalink
final changes
Browse files Browse the repository at this point in the history
  • Loading branch information
mschipperheyn committed May 9, 2016
1 parent ba77c99 commit 6007474
Show file tree
Hide file tree
Showing 8 changed files with 423 additions and 1 deletion.
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -2,3 +2,4 @@
node_modules
dist
lib
*.tgz
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@
"src"
],
"author": "Marc Schipperheyn",
"license": "MIT",
"license": "BSD",
"bugs": {
"url": "https://github.com/mschipperheyn/normalizr-immutable/issues"
},
Expand Down
29 changes: 29 additions & 0 deletions package/LICENSE
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@

BSD License

Copyright (c) 2016-present, Ology, Consultoria e Participações. All rights reserved.

Redistribution and use in source and binary forms, with or without modification,
are permitted provided that the following conditions are met:

* Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.

* Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.

* Neither the name Ology nor the names of its contributors may be used to
endorse or promote products derived from this software without specific
prior written permission.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
58 changes: 58 additions & 0 deletions package/package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,58 @@
{
"name": "normalizr-immutable",
"version": "0.0.1",
"description": "Normalizes JSON to immutable Records according to schema for Redux applications and provide proxied access to properties",
"main": "lib/index.js",
"private": false,
"repository": {
"type": "git",
"url": "https://github.com/mschipperheyn/normalizr-immutable.git"
},
"keywords": [
"redux",
"normalize",
"proxy",
"json"
],
"files": [
"dist",
"lib",
"src"
],
"author": "Marc Schipperheyn",
"license": "MIT",
"bugs": {
"url": "https://github.com/mschipperheyn/normalizr-immutable/issues"
},
"homepage": "https://github.com/mschipperheyn/normalizr-immutable",
"scripts": {
"test": "mocha --compilers js:babel-register --harmony-proxies --opts test/mocha.opts test/**/*.spec.js",
"prebuild": "rimraf dist lib",
"build": "webpack && babel src --out-dir lib",
"prepublish": "npm run build"
},
"dependencies": {
"harmony-proxy": "^1.0.1",
"harmony-reflect": "^1.4.6",
"immutable": "^3.7.6",
"lodash": "^4.2.1",
"lodash-es": "^4.2.1",
"normalizr": "^2.0.1"
},
"devDependencies": {
"babel-cli": "^6.8.0",
"babel-loader": "^6.2.4",
"babel-plugin-transform-decorators-legacy": "^1.3.4",
"babel-preset-es2015": "^6.6.0",
"babel-preset-react-native": "^1.7.0",
"babel-preset-react-native-stage-0": "^1.0.1",
"babel-preset-stage-1": "^6.5.0",
"chai": "^3.5.0",
"chai-immutable": "^1.5.4",
"mocha": "^2.4.5",
"redux": "^3.5.2",
"redux-logger": "^2.6.1",
"rimraf": "^2.5.2",
"webpack": "^1.13.0"
}
}
21 changes: 21 additions & 0 deletions package/src/IterableSchema.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
import isObject from 'lodash/isObject';
import UnionSchema from './UnionSchema';

export default class ArraySchema {
constructor(itemSchema, options = {}) {
if (!isObject(itemSchema)) {
throw new Error('ArraySchema requires item schema to be an object.');
}

if (options.schemaAttribute) {
const schemaAttribute = options.schemaAttribute;
this._itemSchema = new UnionSchema(itemSchema, { schemaAttribute })
} else {
this._itemSchema = itemSchema;
}
}

getItemSchema() {
return this._itemSchema;
}
}
259 changes: 259 additions & 0 deletions package/src/NormalizrImmutable.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,259 @@
// Based on Normalizr 2.0.1
'use strict';

// import { arrayOf, valuesOf, unionOf } from 'normalizr';
import { Record, Map, List, Iterable } from 'immutable';

//Shim for new Proxy instead of Proxy.create
import Proxy from 'harmony-proxy';
//Should patch proxy to work properly
import Reflect from 'harmony-reflect';

import RecordEntitySchema from './RecordEntitySchema';
import IterableSchema from './IterableSchema';
import UnionSchema from './UnionSchema';
import lodashIsEqual from 'lodash/isEqual';
import lodashIsObject from 'lodash/isObject';

const NormalizedRecord = new Record({entities:null, result: null});
const PolymorphicMapper = new Record({id:null, schema: null});

function defaultAssignEntity(normalized, key, entity) {
normalized[key] = entity;
}

function proxy(id, schema, bag, options){
/**
* if options contains getState reference and reducer key we can create a proxyHandler
*/

return new Proxy({id: id, key: schema.getKey()},{
get(target, name, receiver) {
// if(name === 'toJSON'){
// console.log(`WARN: use toJSON in stead of JSON.stringify on immutable data structures: ${key}`);
// }
//toString methods create recursive issues
// if(name === 'toJSON' || name === 'toString')
// return () => target;
// if (name === 'valueOf')
// return target[name];
//this method can get called before the normalization process has completed.
//We can always expect entities to be a record, so we can defensively check for existence
//We want to be able to return the id before the state has been initialized
if(name === 'id')
return target.id;

const state = options.getState();

if(state[options.reducerKey].entities){
const ref = Reflect.get(state[options.reducerKey].entities[schema.getKey()][target.id],name);
return ref;
}
return undefined;
},
set(k,v){
throw new Error('Not supported');
},
has(name){
return options.getState()[options.reducerKey].entities[schema.getKey()][id].has(name);
},
valueOf : function () {
return 0;
}
});
}

function visitObject(obj, schema, bag, options) {
const _options$assignEntity = options.assignEntity;
const assignEntity = _options$assignEntity === undefined ? defaultAssignEntity : _options$assignEntity;

let normalized = {};
for (let key in obj) {
if (obj.hasOwnProperty(key)) {
const entity = visit(obj[key], schema[key], bag, options);
assignEntity.call(null, normalized, key, entity, obj);
}
}
return new Map(normalized);
}

function visitRecord(obj, schema, bag, options){
const { assignEntity = defaultAssignEntity } = options;

let normalized = {};

for (let key in obj) {
if (obj.hasOwnProperty(key)) {
const entity = visit(obj[key], schema[key], bag, options);

assignEntity.call(null, normalized, key, entity, obj);
}
}

const Record = schema.getRecord();
return new Record(normalized);
}

function defaultMapper(iterableSchema, itemSchema, bag, options) {
return function (obj) {
return visit(obj, itemSchema, bag, options);
};
}

function polymorphicMapper(iterableSchema, itemSchema, bag, options) {
return function (obj) {
const schemaKey = iterableSchema.getSchemaKey(obj);
const result = visit(obj, itemSchema[schemaKey], bag, options);
return new PolymorphicMapper({ id: result, schema: schemaKey });
};
}

function visitIterable(obj, iterableSchema, bag, options) {
const itemSchema = iterableSchema.getItemSchema();
const curriedItemMapper = defaultMapper(iterableSchema, itemSchema, bag, options);

if (Array.isArray(obj)) {
return new List(obj.map(curriedItemMapper));
} else {
const mp = Object.keys(obj).reduce(function (objMap, key) {
objMap[key] = curriedItemMapper(obj[key]);
return objMap;
}, {});
return new Map(mp);
}
}

function visitUnion(obj, unionSchema, bag, options) {
const itemSchema = unionSchema.getItemSchema();
return polymorphicMapper(unionSchema, itemSchema, bag, options)(obj);
}

function defaultMergeIntoEntity(entityA, entityB, entityKey) {
if(entityA === null)
return entityB;

if(!entityA.equals(entityB)){

console.info(
`When checking two ${entityKey}, found unequal data. Merging the data. You should consider making sure these objects are equal.`,
entityA, entityB
);

return entityA.merge(entityB);
}

return entityA;
}

function visitEntity(entity, entitySchema, bag, options) {
// if(!(entitySchema instanceof RecordEntitySchema))
// throw new Error('Immutable Normalizr expects a Record object as part of the Schema')

const _options$mergeIntoEntity = options.mergeIntoEntity;
const mergeIntoEntity = _options$mergeIntoEntity === undefined ? defaultMergeIntoEntity : _options$mergeIntoEntity;

const entityKey = entitySchema.getKey();
const id = entitySchema.getId(entity);

if (!bag.hasOwnProperty(entityKey)) {
bag[entityKey] = {};
}

if (!bag[entityKey].hasOwnProperty(id)) {
bag[entityKey][id] = null;
}

let stored = bag[entityKey][id];
let normalized = visitRecord(entity, entitySchema, bag, options);
bag[entityKey][id] = mergeIntoEntity(stored, normalized, entityKey);

if(options.getState){
return proxy(id, entitySchema, bag, options);
}

return id;
}

function visit(obj, schema, bag, options = {}) {
if (!lodashIsObject(schema)) {
return obj;
}

if (!lodashIsObject(obj) && schema._mappedBy) {
obj = {
[schema.getIdAttribute()]: obj,
};
} else if (!lodashIsObject(obj)) {
return obj;
}

if (schema instanceof RecordEntitySchema) {
return visitEntity(obj, schema, bag, options);
} else if (schema instanceof IterableSchema) {
return visitIterable(obj, schema, bag, options);
} else if (schema instanceof UnionSchema) {
return visitUnion(obj, schema, bag, options);
} else {
//we want the root object to be processed as a record, all others, not managed by a record should become a Map
return visitObject(obj, schema, bag, options);
}
}

function arrayOf(schema, options) {
return new IterableSchema(schema, options);
}

function valuesOf(schema, options) {
return new IterableSchema(schema, options);
}

function unionOf(schema, options) {
return new UnionSchema(schema, options);
}

function normalize(obj, schema, options = {}) {

if (!lodashIsObject(obj) && !Array.isArray(obj)) {
throw new Error('Normalize accepts an object or an array as its input.');
}

if (!lodashIsObject(schema) || Array.isArray(schema)) {
throw new Error('Normalize accepts an object for schema.');
}

let bag = {};
let entityStructure = {};
let keyStructure = {};
let results = [];
let result = visit(obj, schema, bag, options);

//we are now assuming that the returned "ids" are actually proxies if there is a getState method
results = options.getState?
result.map(function(val){
return val.id;
})
:
result;

for(let schemaKey in bag){
keyStructure[schemaKey] = null;
const ValueStructure = new Record(bag[schemaKey]);
entityStructure[schemaKey] = new ValueStructure({});
}

const EntityStructure = new Record(keyStructure);

return new NormalizedRecord({
entities: new EntityStructure(entityStructure),
result: new List(results)
});
}

export {
NormalizedRecord,
arrayOf,
valuesOf,
unionOf,
normalize,
RecordEntitySchema as Schema
};
Loading

0 comments on commit 6007474

Please sign in to comment.