system-cache
Version:
use cache with this simple helper
86 lines (81 loc) • 2.03 kB
JavaScript
let encrypt = require('crypto-js/sha256');
class childrenCache {
constructor(name, data){
this.name = name;
this.data = data[name];
this.before = data;
}
child(name){
this.before = this;
return new childrenCache(name, this.data);
}
parent(){
return this.before;
}
}
class cacheStorage {
constructor(options){
this.options = options ? options : {};
this.cache = {
date: new Date(),
sha256: encrypt(new Date()).toString(),
base: null
}
}
setOptions(data){
if(!data.regist == true) return console.log(new Error('Configs is registered, Not changes.'));
if(!data) return console.log(new Error('Add data for options.'));
this.options.async = data.async;
this.options.setCache = data.setCache;
this.options.addCache = data.addCache;
this.options.global = data.global;
this.options.execFunction = data.execFunction;
}
setCache(base){
this.cache = {
date: new Date(),
sha256: encrypt(new Date()).toString(),
base: base,
beforeBase: this.cache
}
return this.cache;
}
getCache(func){
if(!this.execFunction) return this.cache.base;
if(!this.options.async) return func(this.cache.base == null ? this.execFunction() : this.cache.base);
return async () => {
const data_received = await this.execFunction();
return func(this.cache.base == null?data_received:this.cache.base);
}
}
clearCache(){
this.beforeBase = [];
}
resetCache(){
this.cache = {
date: new Date(),
sha256: encrypt(new Date()).toString(),
base: null
}
}
encrypt(data){
return {
data,
system: "sha256",
final: encrypt(data),
string: encrypt(data).toString(),
encrypt(){
return encrypt(new Date());
}
};
}
child(name){
return new childrenCache(name, this.cache.base);
}
}
module.exports = cacheStorage;
module.exports.createCache = (options, cache) => {
let type_cache = new cacheStorage(options);
type_cache.cache.base = cache;
return type_cache;
}