jakearchibald / idb

IndexedDB, but with promises
https://www.npmjs.com/package/idb
ISC License
6.29k stars 353 forks source link

Better way to handle ordering/sorting when getting from index #176

Closed belvederef closed 4 years ago

belvederef commented 4 years ago

Thank you for the awesome work. I was wondering if a more straightforward way to handle ordering/sorting could be implemented. Currently, to get the results of an index in ascending order, I am doing:

let cursor = await myDb
  .transaction('articles')
  .store.index('by-timestamp')
  .openCursor(undefined, 'prev');

const articles = []
while (cursor) {
  articles.push(cursor.value)
  cursor = await cursor.continue();
}

But wondering if an easier way could be implemented such that one could call:

const articles = await myDb.getAllFromIndex(
  'articles',
  'by-timestamp',
  undefined,
  20, // count
  'ASC', // order
);

It looks to me like this is pretty commonly used, but maybe there are reasons for not having this feature.

jakearchibald commented 4 years ago

Ascending should be the default, no?

Getting things in reverse order from an index is already pretty easy:

const articles = (await myDb.getAllFromIndex('articles', 'by-timestamp')).reverse();
jakearchibald commented 4 years ago

Please reopen this if it isn't the right answer!

belvederef commented 4 years ago

Sorry, yes ascending is the default, I meant descending order.

Your solution will work in case we are getting all the objects from the store but rarely you would want that. Anyhow, I think this issue needs to first be implemented by the w3c folks.