Skip to content

Instantly share code, notes, and snippets.

@avdeev
Last active June 11, 2020 08:23
Show Gist options
  • Save avdeev/94092fe69b5abe312eeb8fbdbd0d9c35 to your computer and use it in GitHub Desktop.
Save avdeev/94092fe69b5abe312eeb8fbdbd0d9c35 to your computer and use it in GitHub Desktop.
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