feathersjs-ecosystem / feathers-hooks-common

Useful hooks for use with FeathersJS services.
https://hooks-common.feathersjs.com
MIT License
193 stars 90 forks source link

[FR] New Hook: next #717

Open FossPrime opened 1 year ago

FossPrime commented 1 year ago

Steps to reproduce

Problem: Pagination is a pain. It is so much of an ugly pain the pagination docs, don't ever try iterating over paginated results, instead showing how to disable pagination!

Solution: a next iterator hook.

Without Hook:

async function main() {
  allMessages = [];
  let page = 1;
  let result;

  do {
    result = await  app.service('messages').find({
      query: {
        $limit: 10, // Change `10` to the maximum number of messages you want to retrieve per page
        $skip: (page - 1) * 10, // Change `10` to the maximum number of messages you want to retrieve per page
      },
    });

    allMessages.push(...result.data);
    page++;
  } while (result.total > allMessages.length);

  allMessages.forEach(console.log)
}

With the Hook:

const main = async () => {
  const messageResult = await app.service('messages').find()
  for await (const res of messageResult.next) {
    res.forEach(console.log)
  }
}

Note how there is zero math involved in userland. Both userland code and the hook itself is somewhat stateless, every variable is a constant.

Proposed implementation:
https://stackblitz.com/edit/lowdb-qs-browser-nbkcvk?file=index.html%3AL89,app.ts