Limit length array-type of property in Loopback 4 query?

286 Views Asked by At

I've been trying this new framework Loopback 4 and its awesome but I dont know to which point is flexible,I'm having the following model on the database:

{
"id": "string",
"lastUpdate": "2020-10-01T18:10:46.306Z",
"name": "string",
"logo": "string",
"data": [
  {}
]

}

And what I'm trying there is to make a query that returns me the data, but as is an array, it has a lot of data and I would like to paginate it, so I thought on limiting the query. I've achieved a query to look like the following:

{
  "offset": 0,
  "limit": 10,
  "skip": 0,
  "where": {
    "name": {"eq":"BengalaSpain"}
  },
  "fields": {
    "data": true
  }
}

I'm trying to limit the data property to 10, but of course, this dosnt affects the property itself, just the wrapper object around it. Is there any way to achieve what im trying?

Thanks in advance guys!

1

There are 1 best solutions below

0
On

LoopBack 4 filters apply at a Repository level as these constraints are passed to the ORM datasource connectors to be converted into their respective native queries (e.g. TOP 10 for SQL Server).

A possible solution is to link the data field into a Relation. Relations essentially create nested Repositories (e.g. hasManyRepository), hence are able to meet the requirement of isolating data into its own Repository.

To quickly create a relation, remove the property from the Model and re-create it using lb4 relation command.

From there, it would be possible to take advantage of the now-enabled InclusionResolver and write use query:

{
  "where": {
    "name": {"eq":"BengalaSpain"}
  },
  "fields": {
    "data": true
  },
  "include": [
    {
      "relation": "<relation name here>",
      "scope": {
        "limit": 10
      }
    }
  ]
}

A side-effect is the separation of data into its own table. However, this should be done irregardless due to database normalization.