Skip to content

Instantly share code, notes, and snippets.

@RobbieTheWagner
Last active August 10, 2018 16:16
Show Gist options
  • Save RobbieTheWagner/1c0e3cdeca249f3e0b37f5fc2c9e3708 to your computer and use it in GitHub Desktop.
Save RobbieTheWagner/1c0e3cdeca249f3e0b37f5fc2c9e3708 to your computer and use it in GitHub Desktop.
Nested JSONAPI Relationships
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 } };
}
});
rawPayload = {
urn: 'a:1',
title: 'foo title',
series: {
urn: 'b:2',
publishFrequency: {
duration: '1',
unit: 'WEEK'
},
description: 'my desc'
}
}
{
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