-
Notifications
You must be signed in to change notification settings - Fork 89
/
_deserialize.js
191 lines (159 loc) · 5.46 KB
/
_deserialize.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
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
const _forOwn = require('lodash/forOwn')
const _isArray = require('lodash/isArray')
const _isUndefined = require('lodash/isUndefined')
const _isPlainObject = require('lodash/isPlainObject')
const _includes = require('lodash/includes')
const _find = require('lodash/find')
const _get = require('lodash/get')
const _map = require('lodash/map')
const _filter = require('lodash/filter')
const _matches = require('lodash/matches')
const _flatten = require('lodash/flatten')
const Logger = require('../../logger')
const cache = new class {
constructor () { this._cache = [] }
set (type, id, deserializedData) {
this._cache.push({
type: type,
id: id,
deserialized: deserializedData
})
}
get (type, id) {
const match = _find(this._cache, r => r.type === type && r.id === id)
return match && match.deserialized
}
clear () {
this._cache = []
}
}()
function collection (items, included, useCache = false) {
const collection = items.map(item => {
return resource.call(this, item, included, useCache)
})
return collection
}
function resource (item, included, useCache = false) {
if (useCache) {
const cachedItem = cache.get(item.type, item.id)
if (cachedItem) return cachedItem
}
const model = this.modelFor(this.pluralize.singular(item.type))
if (model.options.deserializer) return model.options.deserializer.call(this, item, included)
const deserializedModel = { id: item.id, type: item.type }
_forOwn(item.attributes, (value, attr) => {
let attrConfig = model.attributes[attr]
if (_isUndefined(attrConfig) && attr !== 'id') {
attr = attr.replace(/-([a-z])/g, function (g) { return g[1].toUpperCase() })
attrConfig = model.attributes[attr]
}
if (_isUndefined(attrConfig) && attr !== 'id') {
Logger.warn(`Resource response for type "${item.type}" contains attribute "${attr}", but it is not present on model config and therefore not deserialized.`)
} else {
deserializedModel[attr] = value
}
})
// Important: cache before parsing relationships to avoid infinite loop
cache.set(item.type, item.id, deserializedModel)
_forOwn(item.relationships, (value, rel) => {
let relConfig = model.attributes[rel]
const key = rel
if (_isUndefined(relConfig)) {
rel = rel.replace(/-([a-z])/g, function (g) { return g[1].toUpperCase() })
relConfig = model.attributes[rel]
}
if (_isUndefined(relConfig)) {
Logger.warn(`Resource response for type "${item.type}" contains relationship "${rel}", but it is not present on model config and therefore not deserialized.`)
} else if (!isRelationship(relConfig)) {
Logger.warn(`Resource response for type "${item.type}" contains relationship "${rel}", but it is present on model config as a plain attribute.`)
} else {
deserializedModel[rel] =
attachRelationsFor.call(this, model, relConfig, item, included, key)
}
})
const params = ['meta', 'links']
params.forEach(function (param) {
if (item[param]) {
deserializedModel[param] = item[param]
}
})
return deserializedModel
}
function attachRelationsFor (model, attribute, item, included, key) {
let relation = null
if (attribute.jsonApi === 'hasOne') {
relation = attachHasOneFor.call(this, model, attribute, item, included, key)
}
if (attribute.jsonApi === 'hasMany') {
relation = attachHasManyFor.call(this, model, attribute, item, included, key)
}
return relation
}
function attachHasOneFor (model, attribute, item, included, key) {
if (!item.relationships) {
return null
}
const relatedItems = relatedItemsFor(model, attribute, item, included, key)
if (relatedItems && relatedItems[0]) {
return resource.call(this, relatedItems[0], included, true)
}
const relationshipData = _get(item.relationships, [key, 'data'], false)
if (relationshipData) {
return relationshipData
}
return null
}
function attachHasManyFor (model, attribute, item, included, key) {
if (!item.relationships) {
return null
}
const relatedItems = relatedItemsFor(model, attribute, item, included, key)
if (relatedItems && relatedItems.length > 0) {
return collection.call(this, relatedItems, included, true)
}
const relationshipData = _get(item.relationships, [key, 'data'], false)
if (relationshipData) {
return relationshipData
}
return []
}
function isRelationship (attribute) {
return (_isPlainObject(attribute) && _includes(['hasOne', 'hasMany'], attribute.jsonApi))
}
/*
* == relatedItemsFor
* Returns unserialized related items.
*/
function relatedItemsFor (model, attribute, item, included, key) {
const relationMap = _get(item.relationships, [key, 'data'], false)
if (!relationMap) {
return []
}
if (_isArray(relationMap)) {
return _flatten(_map(relationMap, function (relationMapItem) {
return _filter(included, (includedItem) => {
return isRelatedItemFor(attribute, includedItem, relationMapItem)
})
}))
} else {
return _filter(included, (includedItem) => {
return isRelatedItemFor(attribute, includedItem, relationMap)
})
}
}
function isRelatedItemFor (attribute, relatedItem, relationMapItem) {
let passesFilter = true
if (attribute.filter) {
passesFilter = _matches(relatedItem.attributes, attribute.filter)
}
return (
relatedItem.id === relationMapItem.id &&
relatedItem.type === relationMapItem.type &&
passesFilter
)
}
module.exports = {
cache: cache,
resource: resource,
collection: collection
}