@leyyo/cache
Version:
Common cache library
309 lines (308 loc) • 9.59 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
exports.cacheUtil = void 0;
class CacheUtilImpl {
constructor() {
this.chars = ['|', '/', '>', ':'];
this._converted = {};
this._same = [];
setTimeout(() => this._clear(), 5 * 60000); // 5 minutes
}
_clear() {
this._converted = {};
this._same = [];
setTimeout(() => this._clear(), 5 * 60000); // 5 minutes
}
alphaNumeric(value) {
if (!value) {
return value;
}
if (this._same.includes(value)) {
return value;
}
if (!/[|\/^>:]/.test(value)) {
this._same.push(value);
return value;
}
if (this._converted[value]) {
return this._converted[value];
}
let text = value;
if (text.includes('^')) {
text = text.replace('^', '~#£');
}
this.chars.forEach((c, i) => {
if (text.includes(c)) {
text = text.replace(c, '^' + i);
}
});
this._converted[value] = text;
return text;
}
bindAll(instance) {
// @leyyo
// Get all defined class methods
const methods = Object.getOwnPropertyNames(Object.getPrototypeOf(instance));
const arr = [];
// Bind all methods
methods
.filter(method => (method !== 'constructor'))
.forEach((method) => {
instance[method] = instance[method].bind(instance);
arr.push(method);
});
for (const [method, body] of Object.entries(instance)) {
if (typeof body === 'function' && !arr.includes(method)) {
instance[method] = instance[method].bind(instance);
}
}
}
objectInfo(value) {
var _a;
return `${typeof value}/${(_a = value === null || value === void 0 ? void 0 : value.constructor) === null || _a === void 0 ? void 0 : _a.name}`;
}
checkObject(holder, type, obj, fn) {
if (!obj) {
throw new Error(`Empty ${type}! info: ${this.objectInfo(obj)} in ${holder}`);
}
if (obj['$$leyyoType'] !== Symbol(fn)) {
throw new Error(`Invalid ${type}! info: ${this.objectInfo(obj)} in ${holder}`);
}
}
checkName(holder, type, value, canBeNull) {
value = value !== null && value !== void 0 ? value : null;
if (value === null) {
if (canBeNull) {
return null;
}
throw new Error(`Empty ${type}! info: ${this.objectInfo(value)} in ${holder}`);
}
if (typeof value === 'string') {
value = value.trim();
if (!value) {
value = null;
}
if (!value) {
if (canBeNull) {
return null;
}
throw new Error(`Empty ${type}! info: ${this.objectInfo(value)} in ${holder}`);
}
}
else {
throw new Error(`Invalid ${type}! info: ${this.objectInfo(value)} in ${holder}`);
}
return value;
}
checkLambda(holder, type, lambda, min) {
if (typeof lambda !== 'function') {
throw new Error(`Invalid ${type}! lambda: ${this.objectInfo(lambda)} in ${holder}`);
}
if (min !== undefined && lambda.length < min) {
throw new Error(`Invalid ${type} parameters! min: ${min} in ${holder}`);
}
}
readProp(prop) {
if (prop) {
const builder = prop;
if (typeof builder.$finalize === 'function') {
builder.$finalize();
}
return prop;
}
return {};
}
parseProperties(property, def = []) {
if (property === undefined || property == null) {
return def;
}
switch (typeof property) {
case "string":
const str = property.trim();
return str ? [str] : def;
case "object":
if (Array.isArray(property)) {
const arr = [];
property.forEach(item => {
if (typeof item === 'string') {
const str = item.trim();
if (str) {
arr.push(str);
}
}
});
return arr.length ? arr : def;
}
return def;
default:
return def;
}
}
utcSec(seconds) {
return Math.floor(new Date().getTime() / 1000) + seconds;
}
utcMs(milliseconds) {
return new Date().getTime() + milliseconds;
}
parseOne(value) {
if (value === undefined || value === null) {
return null;
}
if (typeof value === 'string') {
return JSON.parse(value);
}
return value;
}
parseArray(value) {
return this.asArray(value).map((v) => this.parseOne(v));
}
parseObject(value) {
const entries = Object.entries(this.asObject(value));
if (entries.length < 1) {
return {};
}
const parsed = {};
for (const [k, v] of entries) {
parsed[k] = this.parseOne(v);
}
return parsed;
}
jsonOne(value) {
if (value === undefined || value === null) {
return null;
}
return JSON.stringify(value);
}
jsonArray(value) {
return this.asArray(value).map((v) => this.jsonOne(v));
}
jsonObject(value) {
const entries = Object.entries(this.asObject(value));
if (entries.length < 1) {
return {};
}
const parsed = {};
for (const [k, v] of entries) {
parsed[k] = this.jsonOne(v);
}
return parsed;
}
asArray(value) {
if (value === undefined || value === null || !Array.isArray(value) || value.length < 1) {
return [];
}
return value;
}
asKey(value) {
if (value === undefined || value == null) {
return null;
}
switch (typeof value) {
case "string":
const str = value.trim();
return str !== '' ? str : null;
case "number":
case "bigint":
return String(value);
case "boolean":
return value ? 'true' : 'false';
default:
return null;
}
}
asKeys(values) {
if (values === undefined || values == null) {
return null;
}
let arr;
if (Array.isArray(values)) {
arr = values.map(m => this.asKey(m)).filter(f => f !== null);
}
else {
arr = [this.asKey(values)].filter(f => f !== null);
}
return arr.length > 0 ? arr : null;
}
_asObject(value) {
const obj = {};
for (const [k, v] of Object.entries(value)) {
if (typeof k === 'string' && !['symbol', 'function', 'undefined'].includes(typeof v)) {
obj[k] = v;
}
}
return obj;
}
asObject(value) {
if (value === undefined || value === null || typeof value !== 'object') {
return {};
}
if (value instanceof Map) {
return this._asObject(Object.fromEntries(value.entries()));
}
else if (Array.isArray(value)) {
const arr = value;
// @leyyo move, as isTuple
let isTuple = true;
for (const item of arr) {
if (!Array.isArray(item) || item.length !== 2) {
isTuple = false;
break;
}
}
if (isTuple) {
try {
return this._asObject(Object.fromEntries(value));
}
catch (e) {
// for any invalid key case
const obj = {};
let key;
arr.forEach(item => {
key = this.asKey(item[0]);
if (key !== null) {
obj[key] = item[1];
}
});
return this._asObject(obj);
}
}
// not tuple, completely flat array
const obj = {};
let key;
arr.forEach((item, i) => {
if (i % 2 === 0) {
key = this.asKey(item);
}
else if (key !== null) {
obj[key] = item;
}
});
return this._asObject(obj);
}
return this._asObject(value);
}
objectFromKeys(keys, def, values) {
if (def === undefined) {
def = null;
}
const obj = {};
values = this.asArray(values);
if (values.length > 0) {
keys.forEach((k, i) => {
if (values[i] !== undefined) {
obj[k] = values[i];
}
else {
obj[k] = def;
}
});
}
else {
keys.forEach(k => {
obj[k] = def;
});
}
return obj;
}
}
exports.cacheUtil = new CacheUtilImpl();