Skip to content

Instantly share code, notes, and snippets.

@olbboy
Forked from hucancode/README.md
Created September 21, 2022 04:36
Show Gist options
  • Save olbboy/08c3937c5bbb3e2091e0a461d061acb0 to your computer and use it in GitHub Desktop.
Save olbboy/08c3937c5bbb3e2091e0a461d061acb0 to your computer and use it in GitHub Desktop.
Flatten Strapi 4's response JSON
// src/middlewares/flatten-response.js
function flattenArray(obj) {
return obj.map(e => flatten(e));
}
function flattenData(obj) {
return flatten(obj.data);
}
function flattenAttrs(obj) {
let attrs = {};
for (var key in obj.attributes) {
attrs[key] = flatten(obj.attributes[key]);
}
return {
id: obj.id,
...attrs
};
}
function flatten(obj) {
if(Array.isArray(obj)) {
return flattenArray(obj);
}
if(obj && obj.data) {
return flattenData(obj);
}
if(obj && obj.attributes) {
return flattenAttrs(obj);
}
return obj;
}
async function respond(ctx, next) {
await next();
if (!ctx.url.startsWith('/api')) {
return;
}
console.log(`API request (${ctx.url}) detected, transforming response json...`);
ctx.response.body = {
data: flatten(ctx.response.body.data),
meta: ctx.response.body.meta
};
}
module.exports = () => respond;
// config/middlewares.js
module.exports = [
'strapi::errors',
'strapi::security',
'strapi::cors',
'strapi::poweredBy',
'strapi::logger',
'strapi::query',
'strapi::body',
'global::flatten-response',
'strapi::favicon',
'strapi::public',
];
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment