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,
},
})
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 |
Store the cache in memory and make it invalid after the page is refreshed.
Storing the cache in IndexedBD that avoid cache invalid after refresh pages.
Send request directly. Don't use cache.
Try to send the request, if it fails, return the cache.
Return cache if it exists, otherwise send request.
Return cache if it exists And then send request and update cache asynchronously.
Keeps most recently used keys removes least recently used (LRU) keys
淘汰整个键值中最久未使用的键值
Randomly removes keys to make space for the new data added.
随机淘汰任意键值
Keeps frequently used keys removes least frequently used (LFU) keys
淘汰整个键值中最少使用的键值
Removes keys with expire field set to true and the shortest remaining time-to-live (TTL) value
优先淘汰更早过期的键值