UNPKG

vk-bridge-level

Version:
109 lines (108 loc) 3.88 kB
import ModuleError from 'module-error'; import { AbstractLevel, } from 'abstract-level'; import { VkBridgeKeyIterator } from './iterators/key_iterator'; import { VkBridgeIterator } from './iterators/full_iterator'; const KEY_SIZE_LIMIT = 100; const VALUE_SIZE_LIMIT = 4096; const BATCH_LIMIT = 3; export class VkBridgeLevel extends AbstractLevel { constructor(_bridge, options) { const encodings = { utf8: true }; super({ encodings, getMany: true, keyIterator: true, seek: true, snapshots: false }, options); this._bridge = _bridge; } _open(_options, callback) { this.nextTick(callback); } _put(key, value, options, callback) { if (key.length > KEY_SIZE_LIMIT) { return this.nextTick(callback, new ModuleError(`key size must be less or equal ${KEY_SIZE_LIMIT}`, { code: 'LEVEL_INVALID_KEY', })); } if (value.length > VALUE_SIZE_LIMIT) { return this.nextTick(callback, new ModuleError(`value size must be less or equal ${VALUE_SIZE_LIMIT}`, { code: 'LEVEL_INVALID_VALUE', })); } this._bridge .send('VKWebAppStorageSet', { key, value, }) .then(() => { this.nextTick(callback); }) .catch((e) => this.processBridgeError(e, callback)); } _get(key, options, callback) { this._bridge .send('VKWebAppStorageGet', { keys: [key], }) .then(({ keys }) => { if (keys.length === 0) { return this.nextTick(callback, new ModuleError(`Key ${key} was not found`, { code: 'LEVEL_NOT_FOUND', })); } const [{ value }] = keys; this.nextTick(callback, null, value); }) .catch((e) => this.processBridgeError(e, callback)); } _del(key, options, callback) { this._bridge .send('VKWebAppStorageSet', { key, value: '', }) .then(() => { this.nextTick(callback); }) .catch((e) => this.processBridgeError(e, callback)); } _getMany(keys, options, callback) { this._bridge .send('VKWebAppStorageGet', { keys, }) .then(({ keys: returnedKeys }) => { const values = keys.map((key) => { const value = returnedKeys.find(({ key: returnedKey }) => key === returnedKey); return value === null || value === void 0 ? void 0 : value.value; }); this.nextTick(callback, null, values); }) .catch((e) => this.processBridgeError(e, callback)); } _iterator(options) { return new VkBridgeIterator(this, options); } _keys(options) { return new VkBridgeKeyIterator(this, options); } _batch(operations, options, callback) { if (operations.length > BATCH_LIMIT) { return this.nextTick(callback, new ModuleError(`operations size must be less or equal ${BATCH_LIMIT}`, { code: 'LEVEL_BATCH_NOT_OPEN', })); } const fetchedOperations = operations.map((operation) => { switch (operation.type) { case 'del': return this.del(operation.key); case 'put': return this.put(operation.key, operation.value, operation); } }); Promise.all(fetchedOperations) .then(() => this.nextTick(callback)) .catch((e) => this.processBridgeError(e, callback)); } processBridgeError(e, callback) { this.nextTick(callback, new ModuleError(JSON.stringify(e), { code: 'LEVEL_REMOTE_ERROR', })); } }