I have a front end app that requires an array of blog posts from the API, and when you call http://strapi-url/posts/
with a GET request, it returns all the results as objects in an array. Happy days.
Eventually I want to have more complex GET options with query params, so I need to modify the post controller and write a custom function for find()
.
When I modify the find()
function in api/post/controllers/post.js
, and just make it return the result of strapi.query('post').find()
, it returns an object with keys rather than an array.
async find(ctx) {
let entity = await.strapi.query('post').find();
return sanitizeEntity(entity, { model: strapi.models.post });
},
I know I could simply convert it into an array in the front end, but feels like a messy solution, and I would rather understand why it doesn't return an array, and what would be the best way to approach a solution.
The code in sanitizeEntity actually does this. You can check it out in the source code(node_modules/strapi-utils/lib/sanitize-entity.js
). Also you can see this by dropping the sanitizeEntity row - you will get an array from await.strapi.query('post').find()
.
You can run the following test (add a custom endpoint) to see the results:
async test2(ctx) {
let entity = await strapi.query('post').find();
ctx.send({
message: 'okay',
posts: entity,
sanitizedPosts: sanitizeEntity(entity, { model: strapi.models.post })
}, 200);
}
You can solve it by making your own custom sanitize function which returns an array OR by processing the result before returning it like so:
let entity = await strapi.query('post').find();
let sanitizedEntity = sanitizeEntity(entity, { model: strapi.models.post });
//process sanitized results to an array
//return the result as array