All files PaginationStream.ts

93.33% Statements 28/30
90% Branches 9/10
100% Functions 2/2
93.33% Lines 28/30

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 431x         1x     1x 1x 1x   1x 3x 3x 3x   1x 93x 62x 62x 62x 62x   93x 3x 3x 3x   28x 28x 28x   28x 28x   28x 93x     93x 1x  
import { Readable } from 'stream'
import { PaginationList } from './Transloadit'
 
type FetchPage<T> = (pageno: number) => PaginationList<T> | PromiseLike<PaginationList<T>>
 
export class PaginationStream<T> extends Readable {
  private _fetchPage: FetchPage<T>
  private _nitems?: number
  private _pageno = 0
  private _items: T[] = []
  private _itemsRead = 0
 
  constructor(fetchPage: FetchPage<T>) {
    super({ objectMode: true })
    this._fetchPage = fetchPage
  }
 
  override async _read() {
    if (this._items.length > 0) {
      this._itemsRead++
      process.nextTick(() => this.push(this._items.pop()))
      return
    }
 
    if (this._nitems != null && this._itemsRead >= this._nitems) {
      process.nextTick(() => this.push(null))
      return
    }
 
    try {
      const { count, items } = await this._fetchPage(++this._pageno)
      this._nitems = count
 
      this._items = Array.from(items)
      this._items.reverse()
 
      this._read()
    } catch (err) {
      this.emit('error', err)
    }
  }
}