1

In case I've huge records (millions) in my table; How can I paginate them in GET request?

LoopBack 4 official control example doesn't emulate this case. I couldn't find any reference for a real case solution (they mentioned an example for the pagination in skip filter but it's not mentioning how to use it with repository methods ex. find()).

Do you've any example or snippet for that case?

EDIT (I saw someone voted to close this question): The main reason of this question is preventing the front-end developer to make any mistake by calling a huge query may impact on server performance (in case she/he forget to use skip & limit filters).

mbnoimi
  • 490
  • 4
  • 21

1 Answers1

0

One way to emulate pagination is to enforce a limit filter.

LoopBack 4 can handle this for you with Model scopes (permalink):

@model({
  settings: {
    scope: {
      limit: 50,
    },
  },
})
class MyModel extends Entity {/* ... */}

To apply the scope to only a select few endpoints, the Controller can modify the filter before passing it to the Repository function:

class MyController {
  @get('/')
  async find(
    @param.filter(MyModel) filter?: Filter<MyModel>
  ): Promise<MyModel[]> {
    const sanitizedFilter = Object.assign(filter, {limit: 50});
    return this.myRepository.find(sanitizedFilter);
  }
}

Both examples perform the same thing: Enforce a limit on the maximum number of items that can be queried in one request.

To get the next 50 items, the API consumer can add a skip filter to their query to get the next "page":

?filter={skip: 50}
Rifa Achrinza
  • 1,555
  • 9
  • 19
  • Awesome @rifa-achrinza Can I apply a similar solution at repository level? I try to keep my models without any modification (because I use `lb4 discover`). The simple modifications apply on controllers level and the heavy ones in repository level. – mbnoimi Dec 10 '20 at 16:02
  • I tried to apply a filter in repository level but it didn't affect on the result! `const filter = { where: { color: colorStr, }, include: [{ relation: 'todos', limit: 20, }], } ` – mbnoimi Dec 10 '20 at 16:04