-
-
Save olbboy/08c3937c5bbb3e2091e0a461d061acb0 to your computer and use it in GitHub Desktop.
Flatten Strapi 4's response JSON
This file contains hidden or 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 hidden or 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', | |
| ]; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment