UNPKG

vk-bridge-level

Version:
72 lines (71 loc) 2.68 kB
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } return new (P || (P = Promise))(function (resolve, reject) { function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } step((generator = generator.apply(thisArg, _arguments || [])).next()); }); }; import { AbstractKeyIterator } from 'abstract-level'; const ITERATOR_LIMIT = 1000; export class VkBridgeKeyIterator extends AbstractKeyIterator { constructor(db, options) { super(db, options); this.keys = []; this.index = 0; this.isEnd = false; } _next(callback) { if (this.needLoadMore()) { this.loadKeys(Number.isSafeInteger(this.limit) ? this.limit : ITERATOR_LIMIT) .then(() => this.nextInner(callback)) .catch((e) => this.db.processBridgeError(e, callback)); } else { this.nextInner(callback); } } _nextv(size, options, callback) { if (this.needLoadMore(size)) { this.loadKeys(Math.min(size, ITERATOR_LIMIT)) .then(() => this.nextInnerMulti(size, callback)) .catch((e) => this.db.processBridgeError(e, callback)); } else { this.nextInnerMulti(size, callback); } } _seek(target, options) { const i = this.keys.indexOf(target); if (i !== -1) { this.index = i; } } loadKeys(count) { return __awaiter(this, void 0, void 0, function* () { if (this.isEnd) { return; } const { keys } = yield this.db._bridge.send('VKWebAppStorageGetKeys', { offset: this.index, count }); if (keys.length === 0) { this.isEnd = true; return; } this.keys.push(...keys); }); } needLoadMore(size = 1) { return this.index + size > this.keys.length; } nextInner(callback) { const key = this.keys[this.index]; this.index++; this.db.nextTick(callback, null, key); } nextInnerMulti(size, callback) { const keys = this.keys.slice(this.index, this.index + size); this.index += size; this.db.nextTick(callback, null, keys); } }