npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

f-cache-memory

v0.0.11

Published

cache memory

Downloads

22

Readme

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

|parameter|default|description|version| |------|----|------|----| | size?: number | 100 | How many can be cached at most || | expiration?: number | Number.MAX_SAFE_INTEGER | Set 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 method | change in v0.0.7+ |

api

|api|parameter|typeof return|description|version| |----|----|----|----|----| | initCache | data: [string, CacheValueType][] | - | Initialize cached data | initCache in v0.0.7+ | | hasCache | key: string | boolean | Verify if it is in cache || | setCache | key: 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 parameter | expiration in v0.0.3+ | | getCache | key: string | any | Retrieve cache || | deleteCache | key: string | - | Delete Cache || | deleteCacheByStarts | url: string | - | Delete cache based on the prefix of key values || | clearCache | - | - | Clear Cache || | cacheSize | - | number | Cache Size || | getNowCache | - | any | Retrieve the current cache, which defaults to the last one, getPreviousCache/getNextCache/goPostionCache/goAbsPostionCache will affect the current cached value || | getPreviousCache | - | any | Cache the previous cache in the set order || | getNextCache | - | any | Cache the next cache in the set order || | goPostionCache | num: number | any | Retrieve cache relative to the current cache, where 1 is the next and -1 is the previous || | goAbsPostionCache | num: number | any | Retrieve the numth cache in the order set || | getCacheToArray | needTime: 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.