Last active
August 10, 2018 16:16
-
-
Save RobbieTheWagner/1c0e3cdeca249f3e0b37f5fc2c9e3708 to your computer and use it in GitHub Desktop.
Nested JSONAPI Relationships
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function convertRestliEntityToJsonApiDocument(entity, included = []) { | |
let [ type, id ] = entity.urn.split(':'); | |
let attributes = {}; | |
let relationships = {}; | |
let resource = { type, id, attributes, relationships }; | |
let document = { data: resource, included }; | |
Object.keys(entity).forEach(key => { | |
let value = entity[key]; | |
if ( key === 'urn') return; | |
else if (typeof value !== 'object' || value === null) { attributes[key] = value; } | |
else if (!value.hasOwnProperty('urn')) { | |
let type = 'time-span'; | |
let id = `${value.unit}:${value.duration}`; | |
relationships[key] = { data: { type, id } }; | |
included.push({ | |
type, | |
id, | |
attributes: value | |
}); | |
} | |
else { | |
let resource = convertRestliEntityToJsonApiDocument(value, included); | |
included.push(resource.data); | |
relationships[key] = { data: { type: resource.data.type, id: resource.data.id } }; | |
} | |
}); |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
rawPayload = { | |
urn: 'a:1', | |
title: 'foo title', | |
series: { | |
urn: 'b:2', | |
publishFrequency: { | |
duration: '1', | |
unit: 'WEEK' | |
}, | |
description: 'my desc' | |
} | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
{ | |
data: { | |
"id": "8348", | |
"type": "aggregated-season-calc-field", | |
"attributes": {}, | |
"relationships": { | |
"defaultSettings": { | |
"data": { "id": "8348", "type": "default-setting" } | |
}, | |
}, | |
}, | |
"included": [ | |
{ | |
"type": "default-setting", | |
"id": "8348", | |
"attributes": { | |
"startDate": "2020-12-07", | |
"endDate": "2030-12-10", | |
"aaaScheduleId": "4", | |
"xamortScheduleId": "4", | |
"rosEndDate": "2016-12-10", | |
}, | |
"relationships": { | |
"expenseSchedule": { | |
"data": { "type": "aaa-schedule", "id": "1" } | |
} | |
} | |
} | |
] | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment