Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I return only selected certain fields in Strapi?

Tags:

strapi

Pretty straightforward (I hope). I'd like to be able to use the API endpoint and have it only return specified fields. I.E. something like this

http://localhost:1337/api/reference?select=["name"]

Would ideally return something of the form

[{"name": "Ref1"}]

Unfortunately that is not the case, and in actuality it returns the following.

[
{
"contributors": [
{
"username": "aduensing",
"email": "[email protected]",
"lang": "en_US",
"template": "default",
"id_ref": "1",
"provider": "local",
"id": 1,
"createdAt": "2016-07-28T19:39:09.349Z",
"updatedAt": "2016-07-28T19:39:09.360Z"
}
],
"createdBy": {
"username": "aduensing",
"email": "[email protected]",
"lang": "en_US",
"template": "default",
"id_ref": "1",
"provider": "local",
"id": 1,
"createdAt": "2016-07-28T19:39:09.349Z",
"updatedAt": "2016-07-28T19:39:09.360Z"
},
"updatedBy": {
"username": "aduensing",
"email": "[email protected]",
"lang": "en_US",
"template": "default",
"id_ref": "1",
"provider": "local",
"id": 1,
"createdAt": "2016-07-28T19:39:09.349Z",
"updatedAt": "2016-07-28T19:39:09.360Z"
},
"question": {
"createdBy": 1,
"createdAt": "2016-07-28T19:41:33.152Z",
"template": "default",
"lang": "en_US",
"name": "My Question",
"content": "Cool stuff, huh?",
"updatedBy": 1,
"updatedAt": "2016-07-28T19:45:02.893Z",
"id": "579a5ff83af4445c179bd8a9"
},
"createdAt": "2016-07-28T19:44:31.516Z",
"template": "default",
"lang": "en_US",
"name": "Ref1",
"link": "Google",
"priority": 1,
"updatedAt": "2016-07-28T19:45:02.952Z",
"id": "579a60ab5c8592c01f946cb5"
}
]

This immediately becomes problematic in any real world context if I decide to load 10, 20, 30, or more records at once, I and end up loading 50 times the data I needed. More bandwidth is used up, slower load times, etc.

like image 933
Andrew Duensing Avatar asked Jul 28 '16 22:07

Andrew Duensing


1 Answers

How I solved this:

  1. Create custom controller action (for example, 'findPaths') in contributor/controllers/contributor.js
    module.exports = {
       findPaths: async ctx => {
           const result = await strapi
               .query('contributor')
               .model.fetchAll({ columns: ['slug'] }) // here we wait for one column only
           ctx.send(result);
       }
    }
  1. Add custom route (for example 'paths') in contributor/config/routes.json
    {
      "method": "GET",
      "path": "/contributors/paths",
      "handler": "contributor.findPaths",
      "config": {
        "policies": []
      }
    },
  1. Add permission in admin panel for Contributor entity, path action

That's it. Now it shows only slug field from all contributor's records.

http://your-host:1337/contributors/paths
like image 152
idolgoff Avatar answered Sep 19 '22 12:09

idolgoff