@browser-network/database
Version:
A type of distributed database built on top of the distributed browser-network
73 lines (72 loc) • 2.66 kB
JavaScript
(function (factory) {
if (typeof module === "object" && typeof module.exports === "object") {
var v = factory(require, exports);
if (v !== undefined) module.exports = v;
}
else if (typeof define === "function" && define.amd) {
define(["require", "exports"], factory);
}
})(function (require, exports) {
"use strict";
exports.__esModule = true;
exports.LocalDB = void 0;
var buildStorageShim = function () {
// @ts-ignore
var localStorageShim = {};
localStorageShim.setItem = function (key, val) {
localStorageShim[key] = val;
};
localStorageShim.getItem = function (key) {
return localStorageShim[key];
};
localStorageShim.removeItem = function (key) {
delete localStorageShim[key];
};
return localStorageShim;
};
var LocalDB = /** @class */ (function () {
function LocalDB(appId) {
var _this = this;
this.keyPrefix = 'db';
this.getByKey = function (key) {
var gotten = _this.localStorage.getItem(key);
if (!gotten)
return null;
return JSON.parse(gotten);
};
this.appId = appId;
this.localStorage = globalThis.localStorage || buildStorageShim();
}
LocalDB.prototype.set = function (val, address) {
var key = this.buildKey(address);
this.localStorage.setItem(key, JSON.stringify(val));
};
LocalDB.prototype.get = function (address) {
var key = this.buildKey(address);
return this.getByKey(key);
};
LocalDB.prototype.getAll = function () {
var _this = this;
var lsKeys = Object.keys(this.localStorage);
var ourKeys = lsKeys.filter(function (key) { return key.indexOf(_this.buildKey('')) > -1; });
return ourKeys.map(this.getByKey);
};
// Remove a single item
LocalDB.prototype.remove = function (address) {
var key = this.buildKey(address);
this.localStorage.removeItem(key);
};
// Remove all items
LocalDB.prototype.clear = function () {
var _this = this;
this.getAll().forEach(function (wrapped) {
_this.remove(wrapped.id);
});
};
LocalDB.prototype.buildKey = function (address) {
return "".concat(this.keyPrefix, "-").concat(this.appId, "-").concat(address);
};
return LocalDB;
}());
exports.LocalDB = LocalDB;
});