@hm-soft/ttl-cache
v0.1.0
Published
TTL 만료 + LRU 인메모리 캐시 — getOrSet/비동기 메모이즈, 시간 주입 가능 (의존성 0)
Maintainers
Readme
@hm-soft/ttl-cache
TTL 만료 + LRU 인메모리 캐시. 의존성 0, 시간 주입 가능(테스트 친화).
설치
npm install @hm-soft/ttl-cache사용
import { TtlCache } from "@hm-soft/ttl-cache";
const cache = new TtlCache<string, User>({ ttlMs: 60_000, maxSize: 1000 });
cache.set("u1", user);
cache.get("u1"); // User | undefined (만료 시 undefined)
cache.has("u1");
// API 호출 결과 메모이즈 (60초 캐시)
const user = await cache.getOrSetAsync("u2", () => fetchUser("u2"));
// 동기 계산 메모이즈
const total = cache.getOrSet("sum", () => heavyCompute());API
| 멤버 | 설명 |
|------|------|
| new TtlCache({ ttlMs?, maxSize?, now? }) | 기본 TTL·용량·시간함수 |
| set(key, value, ttlMs?) | 저장(항목별 TTL 가능) |
| get(key) | 조회(만료면 undefined) |
| has(key) | 유효 키 존재 여부 |
| delete(key) / clear() | 제거 |
| prune() | 만료 항목 일괄 정리 |
| size / keys() | 유효 항목 수/키 |
| getOrSet(key, factory, ttlMs?) | 없으면 계산 후 캐시 |
| getOrSetAsync(key, factory, ttlMs?) | 비동기 메모이즈 |
ttlMs0 또는 미지정 → 기본 만료 없음 (항목별set(k,v,ttl)로 개별 지정 가능)maxSize초과 시 가장 오래 안 쓴 항목(LRU)부터 제거now를 주입하면 시간 의존 로직을 결정적으로 테스트 가능
License
Apache-2.0
