-
Notifications
You must be signed in to change notification settings - Fork 32
Expand file tree
/
Copy pathserializer.js
More file actions
511 lines (446 loc) · 13.1 KB
/
serializer.js
File metadata and controls
511 lines (446 loc) · 13.1 KB
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
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
'use strict'
var _ = require('lodash')
var RelUtils = require('./utilities/relationship-utils')
var utils = require('./utils')
function defaultBeforeSerialize (options, cb) {
cb(null, options)
}
function defaultSerialize (options, cb) {
var result = null
var resultData = {}
if (_.isArray(options.results)) {
result = parseCollection(
options.type,
options.results,
options.relationships,
options
)
} else if (_.isPlainObject(options.results)) {
result = parseResource(
options.type,
options.results,
options.relationships,
options
)
}
if (options.topLevelLinks) {
resultData.links = makeLinks(options.topLevelLinks)
}
resultData.data = result
if (options.meta) resultData.meta = options.meta
/**
* If we're requesting to sideload relationships...
*/
if (options.requestedIncludes) {
try {
handleIncludes(
resultData,
options.requestedIncludes,
options.relationships,
options
)
} catch (err) {
cb(err)
}
}
options.results = resultData
cb(null, options)
}
function defaultAfterSerialize (options, cb) {
cb(null, options)
}
module.exports = function serializer (type, data, relations, options, cb) {
options = _.clone(options)
options.attributes = options.attributes || {}
options.isRelationshipRequest = false
if (options.topLevelLinks.self.match(/\/relationships\//)) {
options.topLevelLinks.related = options.topLevelLinks.self.replace(
'/relationships/',
'/'
)
options.isRelationshipRequest = true
}
var serializeOptions
var model = options.model
var beforeSerialize = typeof model.beforeJsonApiSerialize === 'function'
? model.beforeJsonApiSerialize
: defaultBeforeSerialize
var serialize = typeof model.jsonApiSerialize === 'function'
? model.jsonApiSerialize
: defaultSerialize
var afterSerialize = typeof model.afterJsonApiSerialize === 'function'
? model.afterJsonApiSerialize
: defaultAfterSerialize
serializeOptions = _.assign(options, {
type: type,
results: data,
relationships: _.cloneDeep(relations)
})
beforeSerialize(serializeOptions, function (err, serializeOptions) {
if (err) return cb(err)
serialize(serializeOptions, function (err, serializeOptions) {
if (err) return cb(err)
afterSerialize(serializeOptions, function (err, serializeOptions) {
if (err) return cb(err)
return cb(null, serializeOptions.results)
})
})
})
}
/**
* Parses a a request and returns a resource
* @private
* @memberOf {Serializer}
* @param {String} type
* @param {Object} data
* @param {Object} relations
* @param {Object} options
* @return {Object|null}
*/
function parseResource (type, data, relations, options) {
var resource = {}
var attributes = {}
var relationships
resource.type = type
relationships = parseRelations(data, relations, options)
if (!_.isEmpty(relationships)) {
resource.relationships = relationships
}
if (options.foreignKeys !== true) {
// Remove any foreign keys from this resource
options.app.models().forEach(function (model) {
_.each(model.relations, function (relation) {
var fkModel = relation.modelTo
var fkName = relation.keyTo
if (utils.relationFkOnModelFrom(relation)) {
fkModel = relation.modelFrom
fkName = relation.keyFrom
}
if (fkModel === options.model && fkName !== options.primaryKeyField) {
// check options and decide whether to remove foreign keys.
if (
options.foreignKeys !== false && Array.isArray(options.foreignKeys)
) {
for (var i = 0; i < options.foreignKeys.length; i++) {
// if match on model
if (options.foreignKeys[i].model === fkModel.sharedClass.name) {
// if no method specified
if (!options.foreignKeys[i].method) return
// if method match
if (options.foreignKeys[i].method === options.method) return
}
}
}
delete data[fkName]
}
})
})
}
_.each(data, function (value, property) {
if (property === options.primaryKeyField) {
resource.id = _(value).toString()
} else {
if (
!options.attributes[type] ||
_.includes(options.attributes[type], property)
) {
attributes[property] = value
}
}
})
if (_.isUndefined(resource.id)) {
return null
}
// if it's a relationship request
if (options.isRelationshipRequest) {
return resource
}
resource.attributes = attributes
if (options.dataLinks) {
resource.links = makeLinks(options.dataLinks, resource)
}
return resource
}
/**
* Parses a collection of resources
* @private
* @memberOf {Serializer}
* @param {String} type
* @param {Object} data
* @param {Object} relations
* @param {Object} options
* @return {Array}
*/
function parseCollection (type, data, relations, options) {
var result = []
_.each(data, function (value) {
result.push(parseResource(type, value, relations, options))
})
return result
}
/**
* Parses relations from the request.
* @private
* @memberOf {Serializer}
* @param {Object} data
* @param {Object} relations
* @param {Object} options
* @return {Object}
*/
function parseRelations (data, relations, options) {
var relationships = {}
_.each(relations, function (relation, name) {
var fkName = relation.keyTo
// If relation is belongsTo then fk is the other way around
if (utils.relationFkOnModelFrom(relation)) {
fkName = relation.keyFrom
}
var pk = data[options.primaryKeyField]
var fk = data[fkName]
var toType = ''
if (relation.polymorphic && utils.relationFkOnModelFrom(relation)) {
var discriminator = relation.polymorphic.discriminator
var model = options.app.models[data[discriminator]]
toType = utils.pluralForModel(model)
} else {
toType = utils.pluralForModel(relation.modelTo)
}
// Relationship `links` should always be defined unless this is a
// relationship request
if (!options.isRelationshipRequest) {
relationships[name] = {
links: {
related: options.host +
options.restApiRoot +
'/' +
options.modelPath +
'/' +
pk +
'/' +
name
}
}
}
var relationship = null
if (!_.isUndefined(fk) && !relation.multiple) {
if (_.isArray(fk)) {
relationship = makeRelations(toType, fk, options)
} else {
relationship = makeRelation(toType, fk, options)
}
}
// No `data` key should be present unless there is actual relationship data.
if (relationship) {
relationships[name].data = relationship
} else if (relation.type === 'belongsTo') {
relationships[name].data = null
}
if (relation.modelTo === relation.modelFrom) {
delete relationships[name].data
}
})
return relationships
}
/**
* Responsible for making a relations.
* @private
* @memberOf {Serializer}
* @param {String} type
* @param {String|Number} id
* @param {Object} options
* @return {Object|null}
*/
function makeRelation (type, id, options) {
if (!_.includes(['string', 'number'], typeof id) || !id) {
return null
}
return {
type: type,
id: id
}
}
/**
* Handles a creating a collection of relations.
* @private
* @memberOf {Serializer}
* @param {String} type
* @param {Array} ids
* @param {Object} options
* @return {Array}
*/
function makeRelations (type, ids, options) {
var res = []
_.each(ids, function (id) {
res.push(makeRelation(type, id, options))
})
return res
}
/**
* Makes links to an item.
* @private
* @memberOf {Serializer}
* @param {Object} links
* @param {Mixed} item
* @return {Object}
*/
function makeLinks (links, item) {
var retLinks = {}
_.each(links, function (value, name) {
if (_.isFunction(value)) {
retLinks[name] = value(item)
} else {
retLinks[name] = _(value).toString()
}
})
return retLinks
}
/**
* Handles serializing the requested includes to a seperate included property
* per JSON API spec.
* @private
* @memberOf {Serializer}
* @param {Object} resp
* @param {Array<String>|String}
* @throws {Error}
* @return {undefined}
*/
function handleIncludes (resp, includes, relations, options) {
var app = options.app
relations = utils.setIncludedRelations(relations, app)
var resources = _.isArray(resp.data) ? resp.data : [resp.data]
if (typeof includes === 'string') {
includes = [includes]
}
if (!_.isArray(includes)) {
throw RelUtils.getInvalidIncludesError(
'JSON API unable to detect valid includes'
)
}
var embedded = resources.map(function subsituteEmbeddedForIds (resource) {
return includes.map(function (include) {
var relation = relations[include]
var includedRelations = relations[include].relations
var propertyKey = relation.keyFrom
var plural = ''
if (relation.polymorphic && utils.relationFkOnModelFrom(relation)) {
var descriminator = relation.polymorphic.discriminator
var discriminator = resource.attributes[descriminator]
plural = utils.pluralForModel(app.models[discriminator])
} else {
plural = utils.pluralForModel(relation.modelTo)
}
var embeds = []
// If relation is belongsTo then pk and fk are the other way around
if (utils.relationFkOnModelFrom(relation)) {
propertyKey = relation.keyTo
}
if (!relation) {
throw RelUtils.getInvalidIncludesError(
'Can\'t locate relationship "' + include + '" to include'
)
}
resource.relationships[include] = resource.relationships[include] || {}
if (resource.relationships[include] && resource.attributes[include]) {
if (_.isArray(resource.attributes[include])) {
embeds = resource.attributes[include].map(function (rel) {
rel = utils.clone(rel)
return createCompoundIncludes(
rel,
propertyKey,
relation.keyTo,
plural,
includedRelations,
options
)
})
embeds = _.compact(embeds)
const included = resource.attributes[include]
resource.relationships[include].data = included.map(relData => {
return {
id: String(relData[propertyKey]),
type: plural
}
})
} else {
var rel = utils.clone(resource.attributes[include])
var compoundIncludes = createCompoundIncludes(
rel,
propertyKey,
relation.keyFrom,
plural,
includedRelations,
options
)
resource.relationships[include].data = {
id: String(resource.attributes[include][propertyKey]),
type: plural
}
embeds.push(compoundIncludes)
}
delete resource.attributes[relation.keyFrom]
delete resource.attributes[relation.keyTo]
delete resource.attributes[include]
}
return embeds
})
})
if (embedded.length) {
// This array may contain duplicate models if the same item is referenced multiple times in 'data'
var duplicate = _.flattenDeep(embedded)
// So begin with an empty array that will only contain unique items
var unique = []
// Iterate through each item in the first array
duplicate.forEach(function (d) {
// Count the number of items in the unique array with matching 'type' AND 'id'
// Since we're adhering to the JSONAPI spec, both 'type' and 'id' can assumed to be present
// Both 'type' and 'id' are needed for comparison because we could theoretically have objects of different
// types who happen to have the same 'id', and those would not be considered duplicates
var count = unique.filter(function (u) {
return u.type === d.type && u.id === d.id
}).length
// If there are no matching entries, then add the item to the unique array
if (count === 0) {
unique.push(d)
}
})
resp.included = unique
}
}
/**
* Creates a compound include object.
* @private
* @memberOf {Serializer}
* @param {Object} relationship
* @param {String} key
* @param {String} fk
* @param {String} type
* @param {Object} includedRelations
* @param {Object} options
* @return {Object}
*/
function createCompoundIncludes (
relationship,
key,
fk,
type,
includedRelations,
options
) {
var compoundInclude = makeRelation(type, String(relationship[key]))
if (options && !_.isEmpty(includedRelations)) {
var defaultModelPath = options.modelPath
options.modelPath = type
compoundInclude.relationships = parseRelations(
relationship,
includedRelations,
options
)
options.modelPath = defaultModelPath
}
// remove the id key since its part of the base compound document, not part of attributes
delete relationship[key]
delete relationship[fk]
// The rest of the data goes in the attributes
compoundInclude.attributes = relationship
return compoundInclude
}