-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathserialize.js
51 lines (46 loc) · 1.13 KB
/
serialize.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
const serializeObject = (obj, ...args) => {
if (!obj) {
return null
}
if (obj.toJson instanceof Function) {
return obj.toJson(...args)
}
if (obj.toJSON instanceof Function) {
return obj.toJSON(...args)
}
return obj
}
const serialize = (obj, ...args) => {
if (Array.isArray(obj)) {
return obj.map(item => serialize(item, ...args))
}
return serializeObject(obj, ...args)
}
const aggregateEntries = (aggr, [field, value]) =>
Object.assign(aggr, {
[field]: value,
})
const filterLinks = links =>
Object.entries(links)
.filter(([, href]) => Boolean(href))
.reduce(aggregateEntries, {})
export const linkCollection = (data, links) =>
linkObject({ _data: serialize(data) }, links)
export const linkObject = (object, links) => {
if (!object) {
return null
}
const serializedLinks = filterLinks({
// eslint-disable-next-line no-underscore-dangle
...object?._links,
...links,
})
const serializedObject = serialize(object)
if (Object.keys(serializedLinks).length === 0) {
return serializedObject
}
return {
...serializedObject,
_links: serializedLinks,
}
}