import { reactive, ref, Ref, UnwrapNestedRefs, UnwrapRef, watch } from "vue";
import { Cache } from "./cache";
/**
* Storage caches ref and reactive to implement listening
*/
class CachedProxy<T extends Object> {
constructor(isRef, cachedKey, value?, isCached?: boolean, isSessionCached?: boolean) {
isCached = isCached ?? true;
isSessionCached = isSessionCached ?? true;
if (isCached) {
this.cachedObj = new Cache(cachedKey, isSessionCached ? 'session' : 'local'); }
const val = this.cachedObj.isEmpty ? (isRef ? value : (value || {})) : this.cachedObj.json
this.proxy = isRef ? ref<T>(val) : reactive<T>(val);
}
/**
* proxy object
*/
proxy: UnwrapNestedRefs<T> | Ref<UnwrapRef<T>>;
cachedObj: Cache;
/**
* Cancel the listening event
*/
watchStop: WatchStopHandle;
/**
* Set object listening events and cache listening objects
* @paramcallback callback function with parameters (current, prev)
*/
watch(callback?: Function) {
this.watchStop = watch(this.proxy, (current, prev) => {
if (this.cachedObj) {
this.cachedObj.setValue(JSON.stringify(current)); // cache
}
callback && callback(current, prev);
},
{ immediate: true });
}
stopWatch() {
this.watchStop && this.watchStop();
}
}
/**
* Storage cache reactive, implement listening
*/
export class CachedReactive<T extends Object> extends CachedProxy<T> {
constructor(cachedKey, value?, isCached?: boolean) {
super(false, cachedKey, value, isCached);
}
/**
* reactive object
*/
declare proxy: UnwrapNestedRefs<T>;
}
/**
* Storage cache ref to implement listening
*/
export class CachedRef<T extends Object> extends CachedProxy<T> {
constructor(cachedKey, value?, isCached?: boolean) {
super(true, cachedKey, value, isCached);
}
/**
* ref object
*/
declare proxy: Ref<UnwrapRef<T>>;
}