keq-cache
TypeScript icon, indicating that this package has built-in type declarations

1.0.0 • Public • Published

keq-cache

version downloads dependencies license Codecov

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({
      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")
  .option({
    cache: {
      strategy: Strategy.NETWORK_FIRST,
      key: 'custom-cache-key',
      ttl: 1000,
    },
  });

Configuration

Name Default Description
storage Storage.Memory See More
maxStorageSize 2MB 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

Memory

Store the cache in memory and make it invalid after the page is refreshed.

IndexedDB

Storing the cache in IndexedBD that avoid cache invalid after refresh pages.

Strategies

StaleWhileRevalidate

stale-wile-revalidate

CacheFirst

cache-first

NetworkFirst

network-first

NetworkOnly

network-only

CacheOnly

cache-only

Eviction

LRU

Keeps most recently used keys; removes least recently used (LRU) keys

淘汰整个键值中最久未使用的键值

Random

Randomly removes keys to make space for the new data added.

随机淘汰任意键值

LFU

Keeps frequently used keys; removes least frequently used (LFU) keys

淘汰整个键值中最少使用的键值

TTL

Removes keys with expire field set to true and the shortest remaining time-to-live (TTL) value

优先淘汰更早过期的键值

Dependents (0)

Package Sidebar

Install

npm i keq-cache

Weekly Downloads

5

Version

1.0.0

License

MIT

Unpacked Size

167 kB

Total Files

143

Last publish

Collaborators

  • val.istar.guo