-
-
Notifications
You must be signed in to change notification settings - Fork 42
/
index.js
70 lines (65 loc) · 1.88 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
import { deattribute } from '../deattribute'
import { linkRelationships } from '../linkRelationships'
/**
* Deserialises an array from a JSON-API structure
*
* @param {*} obj The response
* @returns {Object} The deserialised response
* @private
*/
async function deserialiseArray (obj) {
for (let value of await obj.data) {
if (obj.included) value = await linkRelationships(value, obj.included)
if (value.attributes) value = await deattribute(value)
obj.data[obj.data.indexOf(value)] = value
}
return obj
}
/**
* Deserialises a JSON-API response
*
* @param {Object} obj The response
* @returns {Object} The deserialised response
*
* @example <caption>Deserialise with a basic data object</caption>
* await deserialise({
* data: {
* id: '1',
* attributes: { liked: true }
* },
* meta: { hello: 'world' }
* }) // { data: { id: '1', liked: true }, meta: { hello: 'world' } }
*
* @example <caption>Deserialise with relationships</caption>
* await deserialise({
* data: {
* id: '1',
* relationships: {
* user: {
* data: {
* type: 'users',
* id: '2' }
* }
* }
* },
* included: [
* {
* type: 'users',
* id: '2',
* attributes: { slug: 'wopian' }
* }
* ]
* }) // { data: { id: '1', user: { type: 'users', id: '2', slug: 'wopian' } } }
*/
export async function deserialise (obj) {
// Collection of resources
// Note: constructor is currently faster than isArray()
// http://jsben.ch/QgYAV
if (obj.data && obj.data.constructor === Array) obj = await deserialiseArray(obj)
// Single resource with included relationships
else if (obj.included) obj.data = await linkRelationships(obj.data, obj.included)
delete obj.included
// Move attributes to the parent object
if (obj.data && obj.data.attributes) obj.data = await deattribute(obj.data)
return obj
}