Skip to content

Instantly share code, notes, and snippets.

@hucancode
Last active January 18, 2024 03:57
Show Gist options
  • Save hucancode/5b495aabf75fc3b940df3e5f94d5b927 to your computer and use it in GitHub Desktop.
Save hucancode/5b495aabf75fc3b940df3e5f94d5b927 to your computer and use it in GitHub Desktop.
Flatten Strapi 4's response JSON

Update 29/11/2022

There is a plugin on Strapi Marketplace that do this response transforming stuffs in a more configurable way. Checkout this if you are interested.

// 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',
];
@mauriciabad
Copy link

@jonasmarco It works, check that the code was copied well and also your project's tsconfig.json.

Code working in the TS playground.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment