strapi-flatten-graphql
Version:
helper to flatten nested strapi v4 graphql structure including typings
75 lines (74 loc) • 2.58 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
exports.flattenDeep = exports.flattenEntityResponseCollection = exports.flattenEntityResponse = exports.flattenEntity = void 0;
function flattenEntity({ id, attributes }) {
if (id === null || id === undefined || !attributes) {
throw new Error('wrong entity');
}
// Apply flattenDeep to each attribute
const flattenedAttributes = Object.entries(attributes).reduce((acc, [key, value]) => {
acc[key] = flattenDeep(value);
return acc;
}, {});
return Object.assign(Object.assign({}, flattenedAttributes), { id });
}
exports.flattenEntity = flattenEntity;
function flattenEntityResponse(response = {}) {
if (!response) {
throw new Error('wrong entity response');
}
const { data } = response;
if (!data) {
throw new Error('wrong entity response');
}
return flattenEntity(data);
}
exports.flattenEntityResponse = flattenEntityResponse;
function flattenEntityResponseCollection({ data }) {
if (!data) {
throw new Error('wrong entity response collection');
}
return data
.map(flattenEntity)
.filter(Boolean);
}
exports.flattenEntityResponseCollection = flattenEntityResponseCollection;
function isFlattenable(value) {
return typeof value === 'object' && value !== null && '__typename' in value &&
(value.__typename.endsWith('EntityResponse') || value.__typename.endsWith('ResponseCollection'));
}
function flattenDeep(obj) {
if (typeof obj !== 'object' || obj === null) {
return obj;
}
if (isFlattenable(obj)) {
if (Array.isArray(obj.data)) {
return flattenEntityResponseCollection(obj);
}
else if (obj.data) {
return flattenEntityResponse(obj);
}
else {
return undefined; // TODO this may happen only in specific cases
}
}
const result = Array.isArray(obj) ? [] : {};
for (const key in obj) {
if (Object.prototype.hasOwnProperty.call(obj, key)) {
const value = obj[key];
if (isFlattenable(value)) {
if ('data' in value && Array.isArray(value.data)) {
result[key] = flattenEntityResponseCollection(value);
}
else {
result[key] = flattenEntityResponse(value);
}
}
else {
result[key] = flattenDeep(value);
}
}
}
return result;
}
exports.flattenDeep = flattenDeep;