Last active
June 11, 2020 08:23
-
-
Save avdeev/94092fe69b5abe312eeb8fbdbd0d9c35 to your computer and use it in GitHub Desktop.
This file contains 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
import { camelCase, mapKeys } from 'lodash'; | |
function camelizeKeys(object) { | |
return mapKeys(object, (value, key) => camelCase(key)); | |
} | |
export default function parseJsonApi(response, type) { | |
return (response.included || []) | |
.concat(Array.isArray(response.data) ? response.data : [response.data]) | |
.filter((item) => item.type === type) | |
.reduce((previousValue, currentValue) => { | |
const value = { ...previousValue }; | |
value[currentValue.id] = { | |
id: currentValue.id, | |
...camelizeKeys(currentValue.attributes), | |
}; | |
if (currentValue.relationships) { | |
const relationships = camelizeKeys(currentValue.relationships); | |
Object.keys(relationships).forEach((key) => { | |
const relationship = relationships[key].data; | |
if (relationship) { | |
if (Array.isArray(relationship)) { | |
value[currentValue.id][key] = relationship.map((item) => item.id); | |
} else { | |
value[currentValue.id][key] = relationship.id; | |
} | |
} | |
}); | |
} | |
return value; | |
}, {}); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment