@happyvertical/cache

中文文档
0.113.1发布于 2026/11/17ISCTypeScriptES Module近 30 天下载 1.1万

Standardized caching interface supporting Memory, File, and Redis backends

原始使用文档
文档目录11 节
  1. Installation
  2. Quick Start
  3. Providers
  4. Memory
  5. File
  6. Redis
  7. S3
  8. API
  9. Environment Variables
  10. Error Classes
  11. Exported Utilities

@happyvertical/cache

Unified caching interface supporting Memory, File, Redis, and S3 backends with TTL, eviction policies, batch operations, and compression. All providers implement the same CacheProvider interface, so you can swap backends without changing application code.

Installation

pnpm add @happyvertical/cache
# Requires @happyvertical/utils as a peer
# redis and @aws-sdk/client-s3 are bundled

Quick Start

import { getCache } from '@happyvertical/cache';

const cache = await getCache({
  provider: 'memory',
  maxSize: 100 * 1024 * 1024,
  evictionPolicy: 'lru',
});

await cache.set('user:123', { name: 'Alice' }, 3600); // TTL in seconds
const user = await cache.get('user:123');
await cache.delete('user:123');
await cache.close();

Providers

Memory

In-process Map-based cache. No external dependencies. Data lost on restart.

const cache = await getCache({
  provider: 'memory',
  namespace: 'app',
  defaultTTL: 3600,          // seconds
  maxSize: 100 * 1024 * 1024, // bytes (default 100MB)
  maxEntries: 10000,          // default 10k
  evictionPolicy: 'lru',      // 'lru' | 'lfu' | 'fifo'
  checkPeriod: 60000,          // expiration sweep interval in ms
});

File

Stores entries as files on disk with optional gzip compression. Persists across restarts.

const cache = await getCache({
  provider: 'file',
  cacheDir: './cache',         // required
  compression: true,           // gzip (default false)
  maxSize: 500 * 1024 * 1024,  // bytes (default 500MB)
  fileExtension: '.cache',
  checkPeriod: 300000,         // cleanup interval in ms
});

Redis

Distributed cache using the redis npm client. Supports optional gzip compression for large values.

const cache = await getCache({
  provider: 'redis',
  host: 'localhost',
  port: 6379,
  password: 'secret',
  db: 0,
  namespace: 'app',
  enableCompression: true,
  compressionThreshold: 1024, // bytes — only compress values larger than this
  connectTimeout: 5000,       // ms
});

S3

Stores entries as S3 objects. Useful for CI caches that must persist between runs. Compression enabled by default to reduce egress costs.

const cache = await getCache({
  provider: 's3',
  bucket: 'my-cache-bucket',
  prefix: 'cache/',
  region: 'us-east-1',
  compression: true,           // default true
  compressionThreshold: 1024,  // bytes
});

API

All providers implement CacheProvider:

interface CacheProvider {
  get<T>(key: string): Promise<T | undefined>;
  set<T>(key: string, value: T, ttl?: number): Promise<void>;
  has(key: string): Promise<boolean>;
  delete(key: string): Promise<boolean>;
  clear(namespace?: string): Promise<void>;
  keys(pattern?: string): Promise<string[]>;
  getMany<T>(keys: string[]): Promise<Map<string, T>>;
  setMany<T>(entries: Array<{ key: string; value: T; ttl?: number }>): Promise<void>;
  deleteMany(keys: string[]): Promise<number>;
  touch(key: string, ttl: number): Promise<boolean>;
  getStats(): Promise<CacheStats>;
  close(): Promise<void>;
}
  • TTL is always in seconds. Omit for no expiration.
  • keys() accepts glob patterns (user:*, report:2024*).
  • touch() updates TTL without modifying the value. Returns false if the key doesn't exist.
  • Batch ops (getMany, setMany, deleteMany) reduce round-trips, especially for Redis.

Environment Variables

Configuration can be loaded from HAVE_CACHE_* environment variables via @happyvertical/utils/loadEnvConfig. Programmatic options always take precedence.

VariableMaps toNotes
HAVE_CACHE_PROVIDERprovidermemory, file, redis, s3
HAVE_CACHE_NAMESPACEnamespace
HAVE_CACHE_DEFAULT_TTLdefaultTTLseconds
HAVE_CACHE_MAX_SIZEmaxSizebytes (memory/file)
HAVE_CACHE_MAX_ENTRIESmaxEntriesmemory only
HAVE_CACHE_EVICTION_POLICYevictionPolicymemory only
HAVE_CACHE_CACHE_DIRcacheDirfile only
HAVE_CACHE_COMPRESSIONcompressionfile/s3
HAVE_CACHE_HOSThostredis only
HAVE_CACHE_PORTportredis only
HAVE_CACHE_PASSWORDpasswordredis only
HAVE_CACHE_BUCKETbuckets3 only
HAVE_CACHE_PREFIXprefixs3 only
HAVE_CACHE_REGIONregions3 only

Error Classes

All errors extend CacheError(message, code, provider):

  • CacheKeyError — invalid key (empty or >250 chars)
  • CacheConnectionError — backend unreachable (Redis)
  • CacheSizeError — entry would exceed maxSize
  • CacheSerializationError — JSON serialize/deserialize failure

Exported Utilities

Low-level helpers re-exported from shared/utils:

  • isValidKey(key) — check key length constraints
  • calculateSize(value) — approximate JSON byte size
  • matchesPattern(pattern, str) — glob matching
  • formatKey(namespace, key) / extractKey(namespace, fullKey) — namespace prefixing
  • isExpired(expiresAt) / calculateExpiration(ttl) — TTL math
  • serialize(value) / deserialize(json) — JSON wrappers

版本与发布记录

@happyvertical/cache 共发布 132 个版本,首次发布于 2026/06/23;过去 12 个月发布了 132 个版本。

版本发布日期距今
0.113.1latest2026/11/17今天
0.113.02026/11/152 天前
0.112.32026/11/134 天前
0.112.22026/11/125 天前
0.112.12026/11/125 天前
0.112.02026/11/125 天前

关于 @happyvertical/cache 的常见问题

@happyvertical/cache 是什么?

Standardized caching interface supporting Memory, File, and Redis backends

如何安装 @happyvertical/cache?

在项目目录运行 npm install @happyvertical/cache,或使用 pnpm add / yarn add / bun add。它还提供命令行工具 have-cache-context,可以用 npx have-cache-context 直接运行。

@happyvertical/cache 支持 TypeScript 吗?

支持。包内自带 TypeScript 类型声明(package.json 声明了 types 入口),安装后即可获得类型提示,无需再安装 @types 包。

@happyvertical/cache 支持 ESM 还是 CommonJS?

以 ES Module 形式发布,推荐使用 import 引入。在 CommonJS 项目中,Node.js 20.19+ / 22.12+ 可以直接 require() 不含顶层 await 的 ES Module,更早的版本需要改用动态 import()。

@happyvertical/cache 可以商用吗?

@happyvertical/cache 使用 ISC 许可。宽松许可:允许商业使用、修改和再分发,通常只需在分发时保留原版权与许可声明。以上为概括,不构成法律意见,请以许可原文为准。

@happyvertical/cache 的下载量有多少?

根据 npm 官方下载统计,@happyvertical/cache 在 2026/10/17 – 2026/11/15 这 30 天内被下载 11,375 次,日均约 379 次。下载量会把 CI 构建、镜像同步和作为其他包依赖的安装一并计入,适合横向比较热度,不能直接等同于使用人数。

@happyvertical/cache 还在维护吗?

最新版本 0.113.1 发布于 2026/11/17(今天);至今共发布 132 个版本,其中过去 12 个月发布了 132 个;首次发布于 2026/06/23。发布频率只是参考信号:功能稳定的工具可能很少需要更新,建议结合源码仓库的 issue 和提交记录判断。