@fnlb-project/stanza
Version:
Modern XMPP in the browser, with a JSON API
65 lines (64 loc) • 2.38 kB
JavaScript
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.createPager = exports.ResultSetPager = void 0;
class ResultSetPager {
constructor(opts) {
var _a, _b, _c;
this.resultComplete = false;
this.fetchedCount = 0;
this.yieldedCount = 0;
this.cursor = { first: opts.before, last: opts.after };
this.query = opts.query;
this.direction = (_a = opts.direction) !== null && _a !== void 0 ? _a : 'forward';
this.reverse = (_b = opts.reverse) !== null && _b !== void 0 ? _b : this.direction === 'backward';
this.pageSize = (_c = opts.pageSize) !== null && _c !== void 0 ? _c : 20;
}
async *[Symbol.asyncIterator]() {
let currentResults = [];
do {
currentResults = await this.fetchPage();
for (const item of currentResults) {
this.yieldedCount += 1;
yield item;
}
} while (currentResults.length > 0);
}
async size() {
if (this.resultCount !== undefined) {
return this.resultCount;
}
const { paging } = await this.query({ max: 0 });
this.resultCount = paging.count;
return paging.count;
}
queryCompleted() {
return this.resultComplete;
}
finished() {
return this.resultComplete && this.yieldedCount === this.fetchedCount;
}
async fetchPage() {
var _a;
const { results, paging } = await this.query({
before: this.direction === 'backward' ? (_a = this.cursor.first) !== null && _a !== void 0 ? _a : '' : undefined,
after: this.direction === 'forward' ? this.cursor.last : undefined,
max: this.pageSize
});
this.cursor = paging;
this.resultCount = paging.count;
this.fetchedCount += results.length;
if ((this.pageSize && results.length < this.pageSize) ||
(this.resultCount && this.fetchedCount === this.resultCount)) {
this.resultComplete = true;
}
if (this.reverse) {
results.reverse();
}
return results;
}
}
exports.ResultSetPager = ResultSetPager;
function createPager(opts) {
return new ResultSetPager(opts);
}
exports.createPager = createPager;