Meteor-Community-Packages / meteor-collection-hooks

Meteor Collection Hooks
https://atmospherejs.com/matb33/collection-hooks
MIT License
658 stars 90 forks source link

After fetch hook? #262

Open Floriferous opened 4 years ago

Floriferous commented 4 years ago

Maybe this is already possible with the current hooks, but I'm not entirely sure:

I'd like all of our limited/skipped mongo queries to also return the total count, without having to manually add this everywhere. This makes it very easy on the front-end to display counts, display a "load more" button (and stop showing it, once you've loaded everything), or simply display a table pagination widget with the total amount of pages.

I believe the place to do this would be in a after.fetch hook: here's roughly what I'd want it to do:

  const cursor = Users.find(query, options);

  const results = cursor.fetch();

  if (results?.length && options?.limit) {
    const count = cursor.count();
    results._queryCount = count;
  }

  return results;

If someone knows of another way to achieve this, or improve the implementation details (e.g. allow toggling this behavio on/off, depending on if you need the count), I'd be happy to learn about it :)

StorytellerCZ commented 4 years ago

Never thought about getting total count in hook like this. I have always used [performant count]( meteor add natestrauser:publish-performant-counts) for that, given the cost of count.

sebakerckhof commented 4 years ago

@StorytellerCZ The package you talk about is for publishing counts (reactive). @Floriferous is talking about a static, one-time count. Like when you would fetch data from an RPC.

An after fetch hook would be a good idea if you want to do this a lot, but it wouldn't be trivial for this package, since fetch is a cursor method and this hooks system currently only works for collection methods.

StorytellerCZ commented 1 year ago

@sebakerckhof got it! I agree, I think this is a bit out of scope. Might be a good idea to extend the fetch method or create a new one where you would call .countFetch() and it would return an object: { data: [...], count: 15 }.