forked from paularmstrong/normalizr
-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
113 lines (88 loc) · 2.45 KB
/
index.js
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
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
'use strict';
var EntitySchema = require('./EntitySchema'),
ArraySchema = require('./ArraySchema'),
isObject = require('lodash/lang/isObject'),
isEqual = require('lodash/lang/isEqual');
function visitObject(obj, schema, bag) {
var normalized = {};
for (var prop in obj) {
if (obj.hasOwnProperty(prop)) {
normalized[prop] = visit(obj[prop], schema[prop], bag);
}
}
return normalized;
}
function visitArray(obj, arraySchema, bag) {
var itemSchema = arraySchema.getItemSchema(),
normalized;
normalized = obj.map(function (childObj) {
return visit(childObj, itemSchema, bag);
});
return normalized;
}
function mergeIntoEntity(entityA, entityB, entityKey) {
for (var prop in entityB) {
if (!entityB.hasOwnProperty(prop)) {
continue;
}
if (!entityA.hasOwnProperty(prop) || isEqual(entityA[prop], entityB[prop])) {
entityA[prop] = entityB[prop];
continue;
}
console.warn(
'When merging two ' + entityKey + ', found shallowly unequal data in their "' + prop + '" values. Using the earlier value.',
entityA[prop], entityB[prop]
);
}
}
function visitEntity(entity, entitySchema, bag) {
var entityKey = entitySchema.getKey(),
idAttribute = entitySchema.getIdAttribute(),
id = entity[idAttribute],
stored,
normalized;
if (!bag[entityKey]) {
bag[entityKey] = {};
}
if (!bag[entityKey][id]) {
bag[entityKey][id] = {};
}
stored = bag[entityKey][id];
normalized = visitObject(entity, entitySchema, bag);
mergeIntoEntity(stored, normalized, entityKey);
return id;
}
function visit(obj, schema, bag) {
if (!isObject(obj) || !isObject(schema)) {
return obj;
}
if (schema instanceof EntitySchema) {
return visitEntity(obj, schema, bag);
} else if (schema instanceof ArraySchema) {
return visitArray(obj, schema, bag);
} else {
return visitObject(obj, schema, bag);
}
}
function normalize(obj, schema) {
if (!isObject(obj) && !Array.isArray(obj)) {
throw new Error('Normalize accepts an object or an array as its input.');
}
if (!isObject(schema) || Array.isArray(schema)) {
throw new Error('Normalize accepts an object for schema.');
}
var bag = {},
result = visit(obj, schema, bag);
return {
entities: bag,
result: result
};
}
function arrayOf(schema) {
return new ArraySchema(schema);
}
module.exports = {
Schema: EntitySchema,
arrayOf: arrayOf,
normalize: normalize
};