flash-store
Version:
FlashStore is a Key-Value persistent storage with easy to use ES6 Map-like API(both Async and Sync support), powered by LevelDB and TypeScript.
967 lines (966 loc) • 45.1 kB
JavaScript
var __generator = (this && this.__generator) || function (thisArg, body) {
var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
function verb(n) { return function (v) { return step([n, v]); }; }
function step(op) {
if (f) throw new TypeError("Generator is already executing.");
while (_) try {
if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
if (y = 0, t) op = [op[0] & 2, t.value];
switch (op[0]) {
case 0: case 1: t = op; break;
case 4: _.label++; return { value: op[1], done: false };
case 5: _.label++; y = op[1]; op = [0]; continue;
case 7: op = _.ops.pop(); _.trys.pop(); continue;
default:
if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
if (t[2]) _.ops.pop();
_.trys.pop(); continue;
}
op = body.call(thisArg, _);
} catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
}
};
var __values = (this && this.__values) || function(o) {
var s = typeof Symbol === "function" && Symbol.iterator, m = s && o[s], i = 0;
if (m) return m.call(o);
if (o && typeof o.length === "number") return {
next: function () {
if (o && i >= o.length) o = void 0;
return { value: o && o[i++], done: !o };
}
};
throw new TypeError(s ? "Object is not iterable." : "Symbol.iterator is not defined.");
};
/* flash-store version 1.0.6 */
(function (global, factory) {
typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports, require('brolog'), require('path'), require('app-root-path'), require('rimraf'), require('level'), require('cuid'), require('state-switch')) :
typeof define === 'function' && define.amd ? define(['exports', 'brolog', 'path', 'app-root-path', 'rimraf', 'level', 'cuid', 'state-switch'], factory) :
(global = typeof globalThis !== 'undefined' ? globalThis : global || self, factory(global.window = {}, global.brolog, global.path, global.appRootPath, global.rimraf, global.level, global.cuid, global.stateSwitch));
}(this, (function (exports, brolog, path, appRootPath, rimraf, level, cuid, stateSwitch) {
'use strict';
function _interopDefaultLegacy(e) { return e && typeof e === 'object' && 'default' in e ? e : { 'default': e }; }
function _interopNamespace(e) {
if (e && e.__esModule)
return e;
var n = Object.create(null);
if (e) {
Object.keys(e).forEach(function (k) {
if (k !== 'default') {
var d = Object.getOwnPropertyDescriptor(e, k);
Object.defineProperty(n, k, d.get ? d : {
enumerable: true,
get: function () {
return e[k];
}
});
}
});
}
n['default'] = e;
return Object.freeze(n);
}
var path__namespace = /*#__PURE__*/ _interopNamespace(path);
var rimraf__default = /*#__PURE__*/ _interopDefaultLegacy(rimraf);
var level__default = /*#__PURE__*/ _interopDefaultLegacy(level);
var cuid__default = /*#__PURE__*/ _interopDefaultLegacy(cuid);
/**
* This file was auto generated from scripts/generate-version.sh
*/
var VERSION = '1.0.6';
/// <reference path="./typings.d.ts" />
// https://github.com/Microsoft/TypeScript/issues/14151#issuecomment-280812617
if (!Symbol.asyncIterator) {
Symbol.asyncIterator = Symbol.for('Symbol.asyncIterator');
}
var __awaiter$1 = (undefined && undefined.__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());
});
};
var __asyncValues$1 = (undefined && undefined.__asyncValues) || function (o) {
if (!Symbol.asyncIterator)
throw new TypeError("Symbol.asyncIterator is not defined.");
var m = o[Symbol.asyncIterator], i;
return m ? m.call(o) : (o = typeof __values === "function" ? __values(o) : o[Symbol.iterator](), i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function () { return this; }, i);
function verb(n) { i[n] = o[n] && function (v) { return new Promise(function (resolve, reject) { v = o[n](v), settle(resolve, reject, v.done, v.value); }); }; }
function settle(resolve, reject, d, v) { Promise.resolve(v).then(function (v) { resolve({ value: v, done: d }); }, reject); }
};
var __await = (undefined && undefined.__await) || function (v) { return this instanceof __await ? (this.v = v, this) : new __await(v); };
var __asyncGenerator = (undefined && undefined.__asyncGenerator) || function (thisArg, _arguments, generator) {
if (!Symbol.asyncIterator)
throw new TypeError("Symbol.asyncIterator is not defined.");
var g = generator.apply(thisArg, _arguments || []), i, q = [];
return i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function () { return this; }, i;
function verb(n) { if (g[n])
i[n] = function (v) { return new Promise(function (a, b) { q.push([n, v, a, b]) > 1 || resume(n, v); }); }; }
function resume(n, v) { try {
step(g[n](v));
}
catch (e) {
settle(q[0][3], e);
} }
function step(r) { r.value instanceof __await ? Promise.resolve(r.value.v).then(fulfill, reject) : settle(q[0][2], r); }
function fulfill(value) { resume("next", value); }
function reject(value) { resume("throw", value); }
function settle(f, v) { if (f(v), q.shift(), q.length)
resume(q[0][0], q[0][1]); }
};
var __asyncDelegator = (undefined && undefined.__asyncDelegator) || function (o) {
var i, p;
return i = {}, verb("next"), verb("throw", function (e) { throw e; }), verb("return"), i[Symbol.iterator] = function () { return this; }, i;
function verb(n, f) { i[n] = o[n] ? function (v) { return (p = !p) ? { value: __await(o[n](v)), done: n === "return" } : f ? f(v) : v; } : f; }
};
var FlashStore = /** @class */ (function () {
/**
* FlashStore is a Key-Value database tool and makes using leveldb more easy for Node.js
*
* Creates an instance of FlashStore.
* @param {string} [workdir=path.join(appRoot, 'flash-store.workdir')]
* @example
* import { FlashStore } from 'flash-store'
* const flashStore = new FlashStore('flashstore.workdir')
*/
function FlashStore(workdir) {
if (workdir === void 0) { workdir = path__namespace.join(appRootPath.path, '.flash-store'); }
this.workdir = workdir;
brolog.log.verbose('FlashStore', 'constructor(%s)', workdir);
// https://twitter.com/juliangruber/status/908688876381892608
// const encoded = encoding<K, V>(
// leveldown(workdir),
// {
// // FIXME: issue #2
// valueEncoding: 'json',
// },
// )
this.levelDb = level__default['default'](workdir);
// console.log((this.levelDb as any)._db.codec)
this.levelDb.setMaxListeners(17); // default is Infinity
}
FlashStore.prototype.version = function () {
return VERSION;
};
/**
* Put data in database
*
* @param {K} key
* @param {V} value
* @returns {Promise<void>}
* @example
* await flashStore.put(1, 1)
*/
FlashStore.prototype.put = function (key, value) {
return __awaiter$1(this, void 0, void 0, function () {
return __generator(this, function (_d) {
switch (_d.label) {
case 0:
brolog.log.warn('FlashStore', '`put()` DEPRECATED. use `set()` instead.');
return [4 /*yield*/, this.set(key, value)];
case 1:
_d.sent();
return [2 /*return*/];
}
});
});
};
FlashStore.prototype.set = function (key, value) {
return __awaiter$1(this, void 0, void 0, function () {
return __generator(this, function (_d) {
switch (_d.label) {
case 0:
brolog.log.verbose('FlashStore', 'set(%s, %s) value type: %s', key, value, typeof value);
// FIXME: issue #2
return [4 /*yield*/, this.levelDb.put(key, JSON.stringify(value))];
case 1:
// FIXME: issue #2
_d.sent();
return [2 /*return*/, this];
}
});
});
};
/**
* Get value from database by key
*
* @param {K} key
* @returns {(Promise<V | null>)}
* @example
* console.log(await flashStore.get(1))
*/
FlashStore.prototype.get = function (key) {
return __awaiter$1(this, void 0, void 0, function () {
var _d, _e, e_6;
return __generator(this, function (_f) {
switch (_f.label) {
case 0:
brolog.log.verbose('FlashStore', 'get(%s)', key);
_f.label = 1;
case 1:
_f.trys.push([1, 3, , 4]);
_e = (_d = JSON).parse;
return [4 /*yield*/, this.levelDb.get(key)];
case 2:
// FIXME: issue #2
return [2 /*return*/, _e.apply(_d, [_f.sent()])];
case 3:
e_6 = _f.sent();
if (/^NotFoundError/.test(e_6)) {
return [2 /*return*/, undefined];
}
throw e_6;
case 4: return [2 /*return*/];
}
});
});
};
/**
* Del data by key
*
* @param {K} key
* @returns {Promise<void>}
* @example
* await flashStore.del(1)
*/
FlashStore.prototype.del = function (key) {
return __awaiter$1(this, void 0, void 0, function () {
return __generator(this, function (_d) {
switch (_d.label) {
case 0:
brolog.log.verbose('FlashStore', '`del()` DEPRECATED. use `delete()` instead');
return [4 /*yield*/, this.delete(key)];
case 1:
_d.sent();
return [2 /*return*/];
}
});
});
};
FlashStore.prototype.delete = function (key) {
return __awaiter$1(this, void 0, void 0, function () {
return __generator(this, function (_d) {
switch (_d.label) {
case 0:
brolog.log.verbose('FlashStore', 'delete(%s)', key);
return [4 /*yield*/, this.levelDb.del(key)];
case 1:
_d.sent();
// TODO: `del` returns `true` or `false`
return [2 /*return*/, true];
}
});
});
};
/**
* @typedef IteratorOptions
*
* @property { any } gt - Matches values that are greater than a specified value
* @property { any } gte - Matches values that are greater than or equal to a specified value.
* @property { any } lt - Matches values that are less than a specified value.
* @property { any } lte - Matches values that are less than or equal to a specified value.
* @property { boolean } reverse - Reverse the result set
* @property { number } limit - Limits the number in the result set.
* @property { any } prefix - Make the same prefix key get together.
*/
/**
* Find keys by IteratorOptions
*
* @param {IteratorOptions} [options={}]
* @returns {AsyncIterableIterator<K>}
* @example
* const flashStore = new FlashStore('flashstore.workdir')
* for await(const key of flashStore.keys({gte: 1})) {
* console.log(key)
* }
*/
FlashStore.prototype.keys = function (options) {
if (options === void 0) { options = {}; }
return __asyncGenerator(this, arguments, function keys_1() {
var e_1, _a, _b, _c, key, e_1_1_1;
return __generator(this, function (_d) {
switch (_d.label) {
case 0:
brolog.log.verbose('FlashStore', 'keys()');
// options = Object.assign(options, {
// keys : true,
// values : false,
// })
if (options.prefix) {
if (options.gte || options.lte) {
throw new Error('can not specify `prefix` with `gte`/`lte` together.');
}
options.gte = options.prefix;
options.lte = options.prefix + '\xff';
}
_d.label = 1;
case 1:
_d.trys.push([1, 8, 9, 14]);
_b = __asyncValues$1(this.entries(options));
_d.label = 2;
case 2: return [4 /*yield*/, __await(_b.next())];
case 3:
if (!(_c = _d.sent(), !_c.done)) return [3 /*break*/, 7];
key = _c.value[0];
return [4 /*yield*/, __await(key)];
case 4: return [4 /*yield*/, _d.sent()];
case 5:
_d.sent();
_d.label = 6;
case 6: return [3 /*break*/, 2];
case 7: return [3 /*break*/, 14];
case 8:
e_1_1_1 = _d.sent();
e_1 = { error: e_1_1_1 };
return [3 /*break*/, 14];
case 9:
_d.trys.push([9, , 12, 13]);
if (!(_c && !_c.done && (_a = _b.return))) return [3 /*break*/, 11];
return [4 /*yield*/, __await(_a.call(_b))];
case 10:
_d.sent();
_d.label = 11;
case 11: return [3 /*break*/, 13];
case 12:
if (e_1)
throw e_1.error;
return [7 /*endfinally*/];
case 13: return [7 /*endfinally*/];
case 14: return [2 /*return*/];
}
});
});
};
/**
* Find all values
*
* @returns {AsyncIterableIterator<V>}
* @example
* const flashStore = new FlashStore('flashstore.workdir')
* for await(const value of flashStore.values()) {
* console.log(value)
* }
*/
FlashStore.prototype.values = function (options) {
if (options === void 0) { options = {}; }
return __asyncGenerator(this, arguments, function values_1() {
var e_2, _a, _b, _c, _d, value, e_2_1_1;
return __generator(this, function (_e) {
switch (_e.label) {
case 0:
brolog.log.verbose('FlashStore', 'values()');
_e.label = 1;
case 1:
_e.trys.push([1, 8, 9, 14]);
_b = __asyncValues$1(this.entries(options));
_e.label = 2;
case 2: return [4 /*yield*/, __await(_b.next())];
case 3:
if (!(_c = _e.sent(), !_c.done)) return [3 /*break*/, 7];
_d = _c.value, value = _d[1];
return [4 /*yield*/, __await(value)];
case 4: return [4 /*yield*/, _e.sent()];
case 5:
_e.sent();
_e.label = 6;
case 6: return [3 /*break*/, 2];
case 7: return [3 /*break*/, 14];
case 8:
e_2_1_1 = _e.sent();
e_2 = { error: e_2_1_1 };
return [3 /*break*/, 14];
case 9:
_e.trys.push([9, , 12, 13]);
if (!(_c && !_c.done && (_a = _b.return))) return [3 /*break*/, 11];
return [4 /*yield*/, __await(_a.call(_b))];
case 10:
_e.sent();
_e.label = 11;
case 11: return [3 /*break*/, 13];
case 12:
if (e_2)
throw e_2.error;
return [7 /*endfinally*/];
case 13: return [7 /*endfinally*/];
case 14: return [2 /*return*/];
}
});
});
};
/**
* Get the counts of the database
* @deprecated use property `size` instead
* @returns {Promise<number>}
* @example
* const count = await flashStore.count()
* console.log(`database count: ${count}`)
*/
FlashStore.prototype.count = function () {
return __awaiter$1(this, void 0, void 0, function () {
var size;
return __generator(this, function (_d) {
switch (_d.label) {
case 0:
brolog.log.warn('FlashStore', '`count()` DEPRECATED. use `size()` instead.');
return [4 /*yield*/, this.size];
case 1:
size = _d.sent();
return [2 /*return*/, size];
}
});
});
};
Object.defineProperty(FlashStore.prototype, "size", {
get: function () {
var _this = this;
brolog.log.verbose('FlashStore', 'size()');
/* eslint no-async-promise-executor: 0 */
// TODO: is there a better way to count all items from the db?
return new Promise(function (resolve, reject) { return __awaiter$1(_this, void 0, void 0, function () {
var e_3, _a, count, _b, _c, _, e_3_1_1, e_7;
return __generator(this, function (_d) {
switch (_d.label) {
case 0:
_d.trys.push([0, 13, , 14]);
count = 0;
_d.label = 1;
case 1:
_d.trys.push([1, 6, 7, 12]);
_b = __asyncValues$1(this);
_d.label = 2;
case 2: return [4 /*yield*/, _b.next()];
case 3:
if (!(_c = _d.sent(), !_c.done)) return [3 /*break*/, 5];
_ = _c.value;
count++;
_d.label = 4;
case 4: return [3 /*break*/, 2];
case 5: return [3 /*break*/, 12];
case 6:
e_3_1_1 = _d.sent();
e_3 = { error: e_3_1_1 };
return [3 /*break*/, 12];
case 7:
_d.trys.push([7, , 10, 11]);
if (!(_c && !_c.done && (_a = _b.return))) return [3 /*break*/, 9];
return [4 /*yield*/, _a.call(_b)];
case 8:
_d.sent();
_d.label = 9;
case 9: return [3 /*break*/, 11];
case 10:
if (e_3)
throw e_3.error;
return [7 /*endfinally*/];
case 11: return [7 /*endfinally*/];
case 12:
resolve(count);
return [3 /*break*/, 14];
case 13:
e_7 = _d.sent();
reject(e_7);
return [3 /*break*/, 14];
case 14: return [2 /*return*/];
}
});
}); });
},
enumerable: false,
configurable: true
});
/**
* FIXME: use better way to do this
*/
FlashStore.prototype.has = function (key) {
return __awaiter$1(this, void 0, void 0, function () {
var val;
return __generator(this, function (_d) {
switch (_d.label) {
case 0: return [4 /*yield*/, this.get(key)];
case 1:
val = _d.sent();
return [2 /*return*/, !!val];
}
});
});
};
/**
* TODO: use better way to do this with leveldb
*/
FlashStore.prototype.clear = function () {
var e_4, _a;
return __awaiter$1(this, void 0, void 0, function () {
var _b, _c, key, e_4_1_1;
return __generator(this, function (_d) {
switch (_d.label) {
case 0:
_d.trys.push([0, 6, 7, 12]);
_b = __asyncValues$1(this.keys());
_d.label = 1;
case 1: return [4 /*yield*/, _b.next()];
case 2:
if (!(_c = _d.sent(), !_c.done)) return [3 /*break*/, 5];
key = _c.value;
return [4 /*yield*/, this.delete(key)];
case 3:
_d.sent();
_d.label = 4;
case 4: return [3 /*break*/, 1];
case 5: return [3 /*break*/, 12];
case 6:
e_4_1_1 = _d.sent();
e_4 = { error: e_4_1_1 };
return [3 /*break*/, 12];
case 7:
_d.trys.push([7, , 10, 11]);
if (!(_c && !_c.done && (_a = _b.return))) return [3 /*break*/, 9];
return [4 /*yield*/, _a.call(_b)];
case 8:
_d.sent();
_d.label = 9;
case 9: return [3 /*break*/, 11];
case 10:
if (e_4)
throw e_4.error;
return [7 /*endfinally*/];
case 11: return [7 /*endfinally*/];
case 12: return [2 /*return*/];
}
});
});
};
Object.defineProperty(FlashStore.prototype, Symbol.toStringTag, {
get: function () {
return Promise.resolve('FlashStore');
},
enumerable: false,
configurable: true
});
FlashStore.prototype[Symbol.iterator] = function () {
brolog.log.verbose('FlashStore', '[Symbol.iterator]()');
/**
* Huan(202108): what is this???
* does it equals to `entries()`?
*/
return this.entries();
};
/**
* @private
*/
FlashStore.prototype.entries = function (options) {
return __asyncGenerator(this, arguments, function entries_1() {
var iterator, pair;
return __generator(this, function (_d) {
switch (_d.label) {
case 0:
brolog.log.verbose('FlashStore', '*entries(%s)', JSON.stringify(options));
iterator = this.levelDb.db.iterator(options);
_d.label = 1;
case 1:
if (!true) return [3 /*break*/, 5];
return [4 /*yield*/, __await(new Promise(function (resolve, reject) {
iterator.next(function (err, key, val) {
if (err) {
reject(err);
}
if (!key && !val) {
return resolve(null);
}
if (val) {
// FIXME: issue #2
val = JSON.parse(val);
}
return resolve([key, val]);
});
}))];
case 2:
pair = _d.sent();
if (!pair) {
return [3 /*break*/, 5];
}
return [4 /*yield*/, __await(pair)];
case 3: return [4 /*yield*/, _d.sent()];
case 4:
_d.sent();
return [3 /*break*/, 1];
case 5: return [2 /*return*/];
}
});
});
};
FlashStore.prototype[Symbol.asyncIterator] = function () {
return __asyncGenerator(this, arguments, function _a() {
var _d;
return __generator(this, function (_e) {
switch (_e.label) {
case 0:
brolog.log.verbose('FlashStore', '*[Symbol.asyncIterator]()');
_d = __await;
return [5 /*yield**/, __values(__asyncDelegator(__asyncValues$1(this.entries())))];
case 1: return [4 /*yield*/, _d.apply(void 0, [_e.sent()])];
case 2:
_e.sent();
return [2 /*return*/];
}
});
});
};
/**
* @private
*/
FlashStore.prototype.streamAsyncIterator = function () {
return __asyncGenerator(this, arguments, function streamAsyncIterator_1() {
var readStream, endPromise, pair, dataPromise;
return __generator(this, function (_d) {
switch (_d.label) {
case 0:
brolog.log.warn('FlashStore', 'DEPRECATED *[Symbol.asyncIterator]()');
readStream = this.levelDb.createReadStream();
endPromise = new Promise(function (resolve, reject) {
readStream
.once('end', function () { return resolve(false); })
.once('error', reject);
});
_d.label = 1;
case 1:
dataPromise = new Promise(function (resolve) {
readStream.once('data', function (data) { return resolve([data.key, data.value]); });
});
return [4 /*yield*/, __await(Promise.race([
dataPromise,
endPromise,
]))];
case 2:
pair = _d.sent();
if (!pair) return [3 /*break*/, 5];
return [4 /*yield*/, __await(pair)];
case 3: return [4 /*yield*/, _d.sent()];
case 4:
_d.sent();
_d.label = 5;
case 5:
if (pair) return [3 /*break*/, 1];
_d.label = 6;
case 6: return [2 /*return*/];
}
});
});
};
FlashStore.prototype.forEach = function (callbackfn, thisArg) {
var e_5, _a;
return __awaiter$1(this, void 0, void 0, function () {
var _b, _c, _d, key, value, e_5_1_1;
return __generator(this, function (_e) {
switch (_e.label) {
case 0:
brolog.log.verbose('FlashStore', 'forEach()');
_e.label = 1;
case 1:
_e.trys.push([1, 6, 7, 12]);
_b = __asyncValues$1(this);
_e.label = 2;
case 2: return [4 /*yield*/, _b.next()];
case 3:
if (!(_c = _e.sent(), !_c.done)) return [3 /*break*/, 5];
_d = _c.value, key = _d[0], value = _d[1];
callbackfn.call(thisArg, value, key, this);
_e.label = 4;
case 4: return [3 /*break*/, 2];
case 5: return [3 /*break*/, 12];
case 6:
e_5_1_1 = _e.sent();
e_5 = { error: e_5_1_1 };
return [3 /*break*/, 12];
case 7:
_e.trys.push([7, , 10, 11]);
if (!(_c && !_c.done && (_a = _b.return))) return [3 /*break*/, 9];
return [4 /*yield*/, _a.call(_b)];
case 8:
_e.sent();
_e.label = 9;
case 9: return [3 /*break*/, 11];
case 10:
if (e_5)
throw e_5.error;
return [7 /*endfinally*/];
case 11: return [7 /*endfinally*/];
case 12: return [2 /*return*/];
}
});
});
};
FlashStore.prototype.close = function () {
return __awaiter$1(this, void 0, void 0, function () {
return __generator(this, function (_d) {
switch (_d.label) {
case 0:
brolog.log.verbose('FlashStore', 'close()');
return [4 /*yield*/, this.levelDb.close()];
case 1:
_d.sent();
return [2 /*return*/];
}
});
});
};
/**
* Destroy the database
*
* @returns {Promise<void>}
*/
FlashStore.prototype.destroy = function () {
return __awaiter$1(this, void 0, void 0, function () {
var _this = this;
return __generator(this, function (_d) {
switch (_d.label) {
case 0:
brolog.log.verbose('FlashStore', 'destroy()');
return [4 /*yield*/, this.levelDb.close()];
case 1:
_d.sent();
return [4 /*yield*/, new Promise(function (resolve) { return rimraf__default['default'](_this.workdir, resolve); })];
case 2:
_d.sent();
return [2 /*return*/];
}
});
});
};
return FlashStore;
}());
FlashStore.VERSION = VERSION;
var __awaiter = (undefined && undefined.__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());
});
};
var __asyncValues = (undefined && undefined.__asyncValues) || function (o) {
if (!Symbol.asyncIterator)
throw new TypeError("Symbol.asyncIterator is not defined.");
var m = o[Symbol.asyncIterator], i;
return m ? m.call(o) : (o = typeof __values === "function" ? __values(o) : o[Symbol.iterator](), i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function () { return this; }, i);
function verb(n) { i[n] = o[n] && function (v) { return new Promise(function (resolve, reject) { v = o[n](v), settle(resolve, reject, v.done, v.value); }); }; }
function settle(resolve, reject, d, v) { Promise.resolve(v).then(function (v) { resolve({ value: v, done: d }); }, reject); }
};
var FlashStoreSync = /** @class */ (function () {
function FlashStoreSync(workdir) {
this.workdir = workdir;
brolog.log.verbose('CacheStore', 'constructor(%s)', workdir);
workdir = workdir || '.flash-store-sync';
this.asyncBusyDict = {};
this.asyncBusyState = new stateSwitch.StateSwitch('Busy:' + workdir.split('/').pop(), // get the latest folder name
brolog.log);
this.cacheMap = new Map();
this.flashStore = new FlashStore(workdir);
this.asyncBusyAdd(this.loadStoreToCache());
}
FlashStoreSync.prototype.loadStoreToCache = function () {
var e_1, _a;
return __awaiter(this, void 0, void 0, function () {
var _b, _c, _d, key, val, e_1_1_2;
return __generator(this, function (_e) {
switch (_e.label) {
case 0:
this.cacheMap.clear();
_e.label = 1;
case 1:
_e.trys.push([1, 6, 7, 12]);
_b = __asyncValues(this.flashStore);
_e.label = 2;
case 2: return [4 /*yield*/, _b.next()];
case 3:
if (!(_c = _e.sent(), !_c.done)) return [3 /*break*/, 5];
_d = _c.value, key = _d[0], val = _d[1];
this.cacheMap.set(key, val);
_e.label = 4;
case 4: return [3 /*break*/, 2];
case 5: return [3 /*break*/, 12];
case 6:
e_1_1_2 = _e.sent();
e_1 = { error: e_1_1_2 };
return [3 /*break*/, 12];
case 7:
_e.trys.push([7, , 10, 11]);
if (!(_c && !_c.done && (_a = _b.return))) return [3 /*break*/, 9];
return [4 /*yield*/, _a.call(_b)];
case 8:
_e.sent();
_e.label = 9;
case 9: return [3 /*break*/, 11];
case 10:
if (e_1)
throw e_1.error;
return [7 /*endfinally*/];
case 11: return [7 /*endfinally*/];
case 12: return [2 /*return*/];
}
});
});
};
FlashStoreSync.prototype.asyncBusyAdd = function (task) {
var _this = this;
this.asyncBusyState.on(true);
var id = cuid__default['default']();
this.asyncBusyDict[id] = task.finally(function () {
delete _this.asyncBusyDict[id];
if (Object.keys(_this.asyncBusyDict).length <= 0) {
_this.asyncBusyState.off(true);
}
});
};
FlashStoreSync.prototype.version = function () {
return this.flashStore.version();
};
/**
*
* Async methods:
*
*/
FlashStoreSync.prototype.close = function () {
return __awaiter(this, void 0, void 0, function () {
return __generator(this, function (_d) {
switch (_d.label) {
case 0: return [4 /*yield*/, this.ready()];
case 1:
_d.sent();
return [4 /*yield*/, this.flashStore.close()];
case 2:
_d.sent();
return [2 /*return*/];
}
});
});
};
FlashStoreSync.prototype.destroy = function () {
return __awaiter(this, void 0, void 0, function () {
var _this = this;
return __generator(this, function (_d) {
this.clear();
// add destroy task at the end of the event loop
this.asyncBusyState.ready('off')
.then(function () { return _this.flashStore.destroy(); }).catch(console.error);
return [2 /*return*/];
});
});
};
FlashStoreSync.prototype.ready = function () {
return __awaiter(this, void 0, void 0, function () {
return __generator(this, function (_d) {
switch (_d.label) {
case 0: return [4 /*yield*/, this.asyncBusyState.ready('off')];
case 1:
_d.sent();
return [2 /*return*/];
}
});
});
};
Object.defineProperty(FlashStoreSync.prototype, "size", {
/*******************************************************
*
*
* The following methods is all for ES6 Map Interface
*
*
*******************************************************/
get: function () {
return this.cacheMap.size;
},
enumerable: false,
configurable: true
});
Object.defineProperty(FlashStoreSync.prototype, Symbol.toStringTag, {
get: function () {
return 'FlashStoreSync';
},
enumerable: false,
configurable: true
});
FlashStoreSync.prototype[Symbol.iterator] = function () {
return this.cacheMap[Symbol.iterator]();
};
FlashStoreSync.prototype.entries = function () {
return this.cacheMap.entries();
};
FlashStoreSync.prototype.keys = function () {
return this.cacheMap.keys();
};
FlashStoreSync.prototype.values = function () {
return this.cacheMap.values();
};
FlashStoreSync.prototype.clear = function () {
this.asyncBusyAdd(this.flashStore.clear());
return this.cacheMap.clear();
};
FlashStoreSync.prototype.delete = function (key) {
this.asyncBusyAdd(this.flashStore.delete(key));
return this.cacheMap.delete(key);
};
/**
* Do not mutate the key/value in the forEach loop!
*/
FlashStoreSync.prototype.forEach = function (callbackfn, thisArg) {
/**
* 1. no need to call flashStore
* 2. callbackfn should not mutate the data, or the data will be lost sync between cache & store
*/
return this.cacheMap.forEach(callbackfn, thisArg);
};
FlashStoreSync.prototype.get = function (key) {
return this.cacheMap.get(key);
};
FlashStoreSync.prototype.has = function (key) {
return this.cacheMap.has(key);
};
FlashStoreSync.prototype.set = function (key, value) {
this.asyncBusyAdd(this.flashStore.set(key, value));
this.cacheMap.set(key, value);
return this;
};
return FlashStoreSync;
}());
FlashStoreSync.VERSION = FlashStore.VERSION;
Object.defineProperty(exports, 'log', {
enumerable: true,
get: function () {
return brolog.log;
}
});
exports.FlashStore = FlashStore;
exports.FlashStoreSync = FlashStoreSync;
exports.VERSION = VERSION;
exports['default'] = FlashStore;
Object.defineProperty(exports, '__esModule', { value: true });
})));
/* https://github.com/huan */
//# sourceMappingURL=flash-store.es6.umd.js.map