keq-cache
v1.0.3
Published
Adds request caching capabilities similar to service workers
Downloads
62
Readme
keq-cache
Usage
import { request } from "keq"
import { cache, Strategy } from "keq-cache"
request.use(cache())
By default, NetworkOnly Strategy and Memory Storage will be used for all request. And you can customize the global configuration:
import { request } from "keq"
import { cache, Strategy } from "keq-cache"
request
.use(
cache({
storage: Storage.MEMORY,
rules: [
{
pattern: (ctx) => ctx.request.method === "get",
strategy: Strategy.STALE_WHILE_REVALIDATE,
ttl: 5 * 60 * 1000,
},
],
})
)
The above configuration, all GET request will use StateWileRevalidate Strategy and cache will expire after 5 minutes.
It is natural to override the global configuration when sending a request:
import { request } from "keq"
import { cache, Strategy, Eviction } from "keq-cache"
request
.get("/example")
.options({
cache: {
strategy: Strategy.NETWORK_FIRST,
key: 'custom-cache-key',
ttl: 1000,
},
})
Configuration
| Name | Default | Description |
| :------------- | :-------------------------------- | :---------------------------------------------------------------------------------------------------------------- |
| storage | Storage.Memory | See More |
| maxStorageSize | Infinity | Maximum storage space occupied by the cache. If exceeded, some cache will be removed according to the Eviction
. |
| threshold | 0.2 * maxStorageSize
| If a request size is greater than threshold, it will not be cached. Don't be larger than maxStorageSize
|
| Eviction | VolatileTTL | Eviction policies when memory is insufficient. See More |
| keyFactory | (context) => context.identifier
| The requested cache unique key factory. Requests with the same key will share the cache |
| rules.pattern | - |
| rules.key | - | The cache key factory for the request match the rule. |
| rules.strategy | NetworkFirst | how generates a response after receiving a fetch. See More |
| rules.ttl | Infinity
| cache time to live |
Storage
Storage.MEMORY
Store the cache in memory and make it invalid after the page is refreshed.
Storage.INDEXED_DB
Storing the cache in IndexedBD that avoid cache invalid after refresh pages.
Strategies
Strategies.NETWORK_ONLY
Send request directly. Don't use cache.
Strategies.NETWORK_FIRST
Try to send the request, if it fails, return the cache.
Strategies.CACHE_FIRST
Return cache if it exists, otherwise send request.
Strategies.STALE_WHILE_REVALIDATE
Return cache if it exists And then send request and update cache asynchronously.
Eviction
Eviction.LRU
Keeps most recently used keys removes least recently used (LRU) keys
淘汰整个键值中最久未使用的键值
Eviction.RANDOM
Randomly removes keys to make space for the new data added.
随机淘汰任意键值
Eviction.LFU
Keeps frequently used keys removes least frequently used (LFU) keys
淘汰整个键值中最少使用的键值
Eviction.TTL
Removes keys with expire field set to true and the shortest remaining time-to-live (TTL) value
优先淘汰更早过期的键值