Last active
June 16, 2022 18:20
-
-
Save zimoo354/09bc7908a3c59982f0f593a72996cf6c to your computer and use it in GitHub Desktop.
Flatten Strapi4 Api Responses
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 | |
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; |
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::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