There is a plugin on Strapi Marketplace that do this response transforming stuffs in a more configurable way. Checkout this if you are interested.
Last active
May 28, 2024 20:51
-
-
Save hucancode/5b495aabf75fc3b940df3e5f94d5b927 to your computer and use it in GitHub Desktop.
Flatten Strapi 4's response JSON
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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; |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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', | |
]; |
@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
🥺