@onesy/cache
Version:
68 lines (67 loc) • 2.2 kB
JavaScript
"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
const merge_1 = __importDefault(require("@onesy/utils/merge"));
const copy_1 = __importDefault(require("@onesy/utils/copy"));
const hash_1 = __importDefault(require("@onesy/utils/hash"));
const unix = () => Math.floor(new Date().getTime() / 1000);
const optionsDefault = {
value: {
copy: false
},
add: {
override: true
},
};
class OnesyCache {
static get options() {
return this.options_;
}
static set options(value) {
this.options_ = (0, merge_1.default)(value, optionsDefault);
}
static add(value, ...args) {
const key = (0, hash_1.default)(args);
if (!this.caches[key] ||
this.options.add.override) {
const value_ = this.options.value.copy ? (0, copy_1.default)(value) : value;
this.caches[key] = {
value: value_,
added_at: unix(),
};
return value_;
}
}
static update(value, ...args) {
const key = (0, hash_1.default)(args);
if (this.caches[key]) {
const value_ = this.options.value.copy ? (0, copy_1.default)(value) : value;
this.caches[key].value = value_;
this.caches[key].updated_at = unix();
return value_;
}
}
static get(...args) {
const key = (0, hash_1.default)(args);
if (this.caches[key])
return this.options.value.copy ? (0, copy_1.default)(this.caches[key].value) : this.caches[key].value;
}
static has(...args) {
const key = (0, hash_1.default)(args);
return this.caches.hasOwnProperty(key);
}
static remove(...args) {
const key = (0, hash_1.default)(args);
if (this.caches.hasOwnProperty(key))
delete this.caches[key];
}
static reset() {
this.caches = {};
this.options = optionsDefault;
}
}
OnesyCache.caches = {};
OnesyCache.options_ = optionsDefault;
exports.default = OnesyCache;