0.0.14 • Published 5 months ago

f-cache-memory v0.0.14

Weekly downloads
-
License
MIT
Repository
github
Last release
5 months ago

f-cache-memory

npm Coverage Status Download

npm i f-cache-memory

中文文档

cache memory library

import CacheMemory from 'f-cache-memory'

const cache = new CacheMemory()
cache.setCache('aaa', 111)
cache.setCache('bbb', 222)
console.log(cache.getCache('aaa'))
console.log(cache.getNowCache())
console.log(cache.getPreviousCache())
cache.setCache('ccc', 333)
console.log(cache.getNowCache())
console.log(cache.getPreviousCache())
console.log(cache.getNextCache())
console.log(cache.getCacheToArray())

const localCache = new CacheMemory(100, 100000, (data) => {
  localStorage.setItem('localCache', JSON.stringify(data))
})
localCache.setCache('aaa', 111)
localCache.setCache('bbb', 222)

const initCache = new CacheMemory()
const localStorageCache = localStorage.getItem('localCache')
if (localStorageCache) {
  initCache.initCache(JSON.parse(localStorageCache))
}
console.log(initCache.getCacheToArray())

Vue:

const cacheList = ref<[string, any][]>([])
const localCache = new CacheMemory(100, 100000, (data) => {
  cacheList.value = data
})

React:

const [cacheList, setCacheList] = useState<[string, any][]>([])
const localCache = new CacheMemory(100, 100000, (data) => {
  setCacheList(data)
})
export interface CacheValueType {
  dateTime: number;
  data: any;
}

Initialize parameters

parameterdefaultdescriptionversion
size?: number100How many can be cached at most
expiration?: numberNumber.MAX_SAFE_INTEGERSet the cache validity period in milliseconds, and if it exceeds the time, it will be deleted
change?: (data: [string, CacheValueType][]) => void-When the cache changes, external data can be synchronized within this methodchange in v0.0.7+

api

apiparametertypeof returndescriptionversion
initCachedata: [string, CacheValueType][]-Initialize cached datainitCache in v0.0.7+
hasCachekey: stringbooleanVerify if it is in cache
setCachekey: string, data: any, expiration?: number-Set cache, expiration sets the cache validity period in milliseconds, with priority higher than the initialized expiration parameter. If not set, it defaults to the initialized expiration parameterexpiration in v0.0.3+
getCachekey: stringanyRetrieve cache
deleteCachekey: string-Delete Cache
deleteCacheByStartsurl: string-Delete cache based on the prefix of key values
clearCache--Clear Cache
cacheSize-numberCache Size
getNowCache-anyRetrieve the current cache, which defaults to the last one, getPreviousCache/getNextCache/goPostionCache/goAbsPostionCache will affect the current cached value
getPreviousCache-anyCache the previous cache in the set order
getNextCache-anyCache the next cache in the set order
goPostionCachenum: numberanyRetrieve cache relative to the current cache, where 1 is the next and -1 is the previous
goAbsPostionCachenum: numberanyRetrieve the numth cache in the order set
getCacheToArrayneedTime: boolean = false[string, CacheValueType][] \| [string, any][]Convert to an array in the order set. If the parameter is false, return the set data directly. If it is true, return {dateTime: expiration time, data: set data}dateTime parameter in v0.0.7+
export interface CacheValueType {
    dateTime: number;
    data: any;
}
export type isArrayNeedTime<T> = T extends true ? [string, CacheValueType][] : [string, any][];
export default class CacheMemory {
    #private;
    constructor(size?: number, expiration?: number, change?: (data: [string, CacheValueType][]) => void);
    hasCache(key: string): boolean;
    setCache(key: string, data: any, expiration?: number): void;
    getCache(key: string): any;
    deleteCache(key: string): void;
    deleteCacheByStarts(url: string): void;
    clearCache(): void;
    initCache(data: [string, CacheValueType][]): void;
    cacheSize(): number;
    getNowCache(): any;
    getPreviousCache(): any;
    getNextCache(): any;
    goPostionCache(num: number): any;
    goAbsPostionCache(num: number): any;
    getCacheToArray<T extends boolean = false>(needTime?: T): isArrayNeedTime<T>;
}

Usage scenario

axios cache

example

// httpCache.ts
import type { AxiosRequestConfig } from 'axios'
import CacheMemory from 'f-cache-memory'

const httpCache = new CacheMemory()
// const httpCache = new CacheMemory(100, 1000)

export function configToKey(config: AxiosRequestConfig): string {
  let key = config.url as string
  if (config.params) {
    key += JSON.stringify(config.params)
  }
  return key
}

export default httpCache

The encapsulation adjustments for axios are as follows

...
import httpCache, { configToKey } from './httpCache'
...
instance.interceptors.response.use(
  (response) => {
    if (response.status === 200 && response.config.method === 'get') {
      const curHttpCacheKey = configToKey(response.config)
      httpCache.setCache(curHttpCacheKey, response)
    }
    return response
  },
  (error) => {
    return Promise.reject(error)
  }
)
...
export function get<T = any>(url: string, config: AxiosRequestConfig = {}): Promise<T> {
  const curHttpCacheKey: string = configToKey({
    url,
    ...config
  })
  if (!httpCache.hasCache(curHttpCacheKey)) {
    const httpRequest = instance.get(url, config)
    httpCache.setCache(curHttpCacheKey, httpRequest)
    return httpRequest as Promise<T>
  } else {
    return Promise.resolve(httpCache.getCache(curHttpCacheKey))
  }
}

Firstly, encapsulate the request and check if it is in the cache before sending the get request. Set the cache value in the interceptors.response.

Fallback function

In some areas that require rollback functionality, this cache supports various caching operations such as getNowCache/getPreviousCache/getNextCache/goPostionCache/goAbsPostionCache.

0.0.14

5 months ago

0.0.12

9 months ago

0.0.13

9 months ago

0.0.11

12 months ago

0.0.10

12 months ago

0.0.8

12 months ago

0.0.6

1 year ago

0.0.5

1 year ago

0.0.3

1 year ago

0.0.2

1 year ago

0.0.1

1 year ago