UNPKG

@ixily/activ

Version:

Alpha Capture Trade Idea Verification. Blockchain ownership proven trade ideas and strategies.

106 lines (90 loc) 2.47 kB
import { CompressorModule, ICacheStorage, ICacheStorageConfig } from '../..' let cache: ICacheStorage | undefined interface ICacheStorageState extends ICacheStorageConfig { configured: boolean } const state: ICacheStorageState = { dbParams: undefined, isBrowser: false as boolean, module: null as any, useCache: true as boolean, configured: false as boolean, } const config = async (_config: ICacheStorageConfig) => { state.dbParams = _config.dbParams state.isBrowser = _config.isBrowser state.module = _config.module state.useCache = _config.useCache cache = _config.module } const inflateStr = async (dt: any): Promise<any> => { if (typeof dt !== 'string') return dt return CompressorModule.inflate(dt) } const deflateStr = async (dt: any): Promise<any> => { if (typeof dt !== 'string') return dt return CompressorModule.deflate(dt) } export const addData = async <T>( key: string, data: T, expiration?: number, ): Promise<void> => { if (!state.useCache) return await asureCache() data = await deflateStr(data) return cache!.addData(key, data, expiration) } const asureCache = async (): Promise<void> => { if (cache === undefined) { throw new Error('CacheStorageModule not configured') } if (!state.configured) { await cache!.config(state) } } export const getData = async <T>(key: string): Promise<T> => { if (!state.useCache) return undefined as T await asureCache() const dt = await cache!.getData(key) const dtInf = await inflateStr(dt) return dtInf as T } export const updateData = async <T>( key: string, data: T, expiration?: number, ): Promise<void> => { if (!state.useCache) return await asureCache() data = await deflateStr(data) return cache!.updateData(key, data, expiration) } export const removeData = async (key: string): Promise<void> => { if (!state.useCache) return await asureCache() return cache!.removeData(key) } export const removeDataByPattern = async (pattern: string): Promise<void> => { if (!state.useCache) return await asureCache() if ((await cache!.removeDataByPattern) !== undefined) { await cache!.removeDataByPattern!(pattern) } else { throw new Error('removeDataByPattern is not defined') } } export const resetData = async (): Promise<void> => { if (!state.useCache) return await asureCache() await cache!.resetData() } export const CacheStorageModule: ICacheStorage = { config, addData, getData, updateData, removeData, removeDataByPattern, resetData, }