jakearchibald / idb

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

PagedResult #206

Closed AbhinavAtul closed 3 years ago

AbhinavAtul commented 3 years ago

Something built on top of the IDBPCursorWithValue

PagedResult {
  constructor(private cursor: IDBPCursorWithValue, private pageSize: number)
  nextPage() : Array<StoreValue> {
   fetchCount = 0 
   let page = new Array<StoreValue>()
   while(this.cursor && fetchCount < this.pageSize){
     page.push(cursor.value)
    ++fetchCount
   }
   return page
  }
}

typescript and its versatile type system, would like to use the solution that currently restricts the type for StoreValue when returning the value from cursor.value to a single type dynamically and thus re-using the paged result throughout all types in the schema

jakearchibald commented 3 years ago

I don't think this needs to be part of the library. Here's a utility function:

import type { StoreNames, IDBPCursorWithValueIteratorValue, StoreValue } from 'idb/with-async-ittr.js';

async function getPageOfResults<
  DBTypes,
  StoreName extends StoreNames<DBTypes> = StoreNames<DBTypes>
>(
  cursorIterator: AsyncIterable<
    IDBPCursorWithValueIteratorValue<DBTypes, StoreNames<DBTypes>[], StoreName>
  >,
  pageSize: number,
): Promise<StoreValue<DBTypes, StoreName>[]> {
  const items: StoreValue<DBTypes, StoreName>[] = [];
  let i = 0;

  for await (const cursor of cursorIterator) {
    items.push(cursor.value);
    i++;
    if (i === pageSize) break;
  }

  return items;
}

async function example() {
  const store = db.transaction('key-val-store').store;
  const result = await getPageOfResults(store, 10);
}

In case anyone wants a plain JavaScript version:

async function getPageOfResults(cursorIterator, pageSize) {
  const items = [];
  let i = 0;

  for await (const cursor of cursorIterator) {
    items.push(cursor.value);
    i++;
    if (i === pageSize) break;
  }

  return items;
}

async function example() {
  const store = db.transaction('key-val-store').store;
  const result = await getPageOfResults(store, 10);
}