Skip to content

Instantly share code, notes, and snippets.

@zimoo354
Last active June 16, 2022 18:20
Show Gist options
  • Save zimoo354/09bc7908a3c59982f0f593a72996cf6c to your computer and use it in GitHub Desktop.
Save zimoo354/09bc7908a3c59982f0f593a72996cf6c to your computer and use it in GitHub Desktop.
Flatten Strapi4 Api Responses
// ./src/middlewares/flatten-response.js
const strapiFlatten = (data) => {
const isObject = (data) => Object.prototype.toString.call(data) === '[object Object]';
const isArray = (data) => Object.prototype.toString.call(data) === '[object Array]';
const flatten = (data) => {
if (!data.attributes) return data;
return {
id: data.id,
...data.attributes,
};
};
if (isArray(data)) {
return data.map((item) => strapiFlatten(item));
}
if (isObject(data)) {
if (isArray(data.data)) {
data = [...data.data];
} else if (isObject(data.data)) {
data = flatten({ ...data.data });
} else if (data.data === null) {
data = null;
} else {
data = flatten(data);
}
for (const key in data) {
data[key] = strapiFlatten(data[key]);
}
return data;
}
return data;
};
async function respond(ctx, next) {
await next();
if (!ctx.url.startsWith("/api")) {
return;
}
if (ctx.response.body)
return ctx.response.body = {
data: strapiFlatten(ctx.response.body.data),
meta: ctx.response.body.meta,
};
return ctx.response.body = {
data: null,
error: { message: 'Not found' },
};
}
module.exports = () => respond;
// ./config/middlewares.js
module.exports = [
// ...
"strapi::body",
'global::flatten-response', // <-- Add this line to integrate the new middleware function
"strapi::session",
// ...
];
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment