@geekmidas/cache

中文文档
9.6.1发布于 2026/11/16TypeScriptESM + CJS构建来源已验证近 30 天下载 1.4万

Unified cache interface with multiple storage implementations

原始使用文档
文档目录33 节
  1. Features
  2. Installation
  3. Optional Dependencies
  4. Quick Start
  5. In-Memory Cache
  6. Redis Cache (Upstash)
  7. File Cache
  8. API Reference
  9. Cache Interface
  10. InMemoryCache
  11. UpstashCache
  12. FileCache
  13. ExpoSecureCache
  14. Advanced Usage
  15. Type Safety
  16. Cache Abstraction
  17. Factory Pattern
  18. Wrapper Pattern
  19. Testing
  20. Mocking
  21. Testing with Real Implementations
  22. Performance Considerations
  23. InMemoryCache
  24. UpstashCache
  25. FileCache
  26. ExpoSecureCache
  27. Key Strategies
  28. Error Handling
  29. Migration Guide
  30. From Map to Cache
  31. From Other Cache Libraries
  32. Contributing
  33. License

@geekmidas/cache

A type-safe, flexible caching library for TypeScript applications with support for multiple cache implementations and a unified interface.

Features

  • Type-safe: Full TypeScript support with generics for strongly-typed cache values
  • Unified interface: Common Cache<T> interface for all implementations
  • Multiple backends: In-memory, Redis (Upstash), Expo Secure Store, and file-based implementations
  • Async API: Promise-based interface for consistency across implementations
  • Flexible TTL: Support for time-to-live across all implementations
  • Easy testing: Simple interface makes mocking and testing straightforward
  • Modular exports: Import only what you need
  • React Native support: Expo Secure Store implementation for mobile apps

Installation

npm install @geekmidas/cache

Optional Dependencies

For Redis support via Upstash:

npm install @upstash/redis

For React Native support via Expo:

npm install expo-secure-store

The file-based cache includes all required dependencies automatically.

Quick Start

In-Memory Cache

Perfect for development, testing, or simple applications:

import { InMemoryCache } from '@geekmidas/cache/memory';

const cache = new InMemoryCache<string>();

// Set a value
await cache.set('user:123', 'John Doe');

// Get a value
const userName = await cache.get('user:123'); // 'John Doe'

// Delete a value
await cache.delete('user:123');

// Check if value exists
const exists = await cache.get('user:123'); // undefined

Redis Cache (Upstash)

For production applications needing distributed caching:

import { UpstashCache } from '@geekmidas/cache/upstash';

const cache = new UpstashCache<User>(
  process.env.UPSTASH_REDIS_URL!,
  process.env.UPSTASH_REDIS_TOKEN!
);

// Set with TTL (1 hour)
await cache.set('user:123', { id: 123, name: 'John Doe' }, 3600);

// Get typed object
const user = await cache.get('user:123'); // User | undefined

// Delete
await cache.delete('user:123');

File Cache

Persistent file-based cache for CLI tools and build systems. Data is stored as JSON on disk and survives process restarts:

import { FileCache } from '@geekmidas/cache/file';

// Default path: process.cwd()/.gkm/cache.json
const cache = new FileCache();

// Custom path and TTL
const cache = new FileCache({
  path: '/tmp/my-app/cache.json',
  ttl: 3600, // 1 hour default TTL
});

// Set a value with TTL (in seconds)
await cache.set('build:hash', 'abc123', 300);

// Get a value
const hash = await cache.get('build:hash'); // string | undefined

// Check remaining TTL
const remaining = await cache.ttl('build:hash'); // seconds

// Delete a value
await cache.delete('build:hash');

API Reference

Cache Interface

All cache implementations follow this interface:

interface Cache<T> {
  get(key: string): Promise<T | undefined>;
  set(key: string, value: T, ttl?: number): Promise<void>;
  delete(key: string): Promise<void>;
}

Methods

get(key: string): Promise<T | undefined>

Retrieves a value from the cache.

  • Parameters: key - The cache key
  • Returns: Promise resolving to the cached value or undefined if not found
  • Example:
    const value = await cache.get('my-key');
    if (value !== undefined) {
      // Use the value
    }
    
set(key: string, value: T, ttl?: number): Promise<void>

Stores a value in the cache.

  • Parameters:
    • key - The cache key
    • value - The value to store
    • ttl - Optional time-to-live in seconds
  • Returns: Promise resolving when the operation completes
  • Example:
    // Set without TTL
    await cache.set('key', 'value');
    
    // Set with 1 hour TTL
    await cache.set('key', 'value', 3600);
    
delete(key: string): Promise<void>

Removes a value from the cache.

  • Parameters: key - The cache key to delete
  • Returns: Promise resolving when the operation completes
  • Example:
    await cache.delete('my-key');
    

InMemoryCache

Simple in-memory cache implementation.

import { InMemoryCache } from '@geekmidas/cache/memory';

class InMemoryCache<T> implements Cache<T>

Features

  • ✅ Fast access (no network latency)
  • ✅ Reference equality for objects
  • ✅ No external dependencies
  • ❌ No TTL support (TTL parameter is ignored)
  • ❌ Data lost on process restart
  • ❌ Not suitable for multi-instance applications

Example

const cache = new InMemoryCache<number>();
await cache.set('counter', 42);
const count = await cache.get('counter'); // 42

UpstashCache

Redis-based cache using Upstash Redis client.

import { UpstashCache } from '@geekmidas/cache/upstash';

class UpstashCache<T> implements Cache<T>

Constructor

new UpstashCache<T>(url: string, token: string)
  • url: Upstash Redis URL
  • token: Upstash Redis token

Features

  • ✅ Persistent storage
  • ✅ TTL support (defaults to 3600 seconds)
  • ✅ Distributed caching
  • ✅ JSON serialization/deserialization
  • ❌ Requires external Redis service
  • ❌ Network latency for operations

Example

interface User {
  id: number;
  name: string;
  email: string;
}

const cache = new UpstashCache<User>(
  'https://your-redis-url.upstash.io',
  'your-token'
);

await cache.set('user:1', {
  id: 1,
  name: 'John Doe',
  email: '[email protected]'
}, 7200); // 2 hours TTL

const user = await cache.get('user:1');

FileCache

Persistent file-based cache that stores entries as JSON on disk.

import { FileCache } from '@geekmidas/cache/file';

class FileCache implements Cache

Constructor

new FileCache(options?: FileCacheOptions)
  • path: Path to the cache JSON file (default: process.cwd()/.gkm/cache.json)
  • ttl: Default TTL in seconds (default: 600)

Features

  • ✅ Persistent storage across process restarts
  • ✅ TTL support with automatic expiration
  • ✅ Safe concurrent writes (in-process mutex + cross-process file locking)
  • ✅ Auto-creates parent directories
  • ✅ No external services required
  • ❌ Not suitable for high-throughput applications
  • ❌ Not suitable for multi-machine distributed caching

Example

const cache = new FileCache({ path: '/tmp/app-cache.json', ttl: 3600 });
await cache.set('config', { theme: 'dark' });
const config = await cache.get('config'); // { theme: 'dark' }
const remaining = await cache.ttl('config'); // ~3600

ExpoSecureCache

Secure storage for React Native apps using Expo SecureStore.

import { ExpoSecureCache } from '@geekmidas/cache/expo';

class ExpoSecureCache<T> implements Cache<T>

Features

  • ✅ Secure, encrypted storage on device
  • ✅ TTL support with automatic expiration
  • ✅ Persistent across app restarts
  • ✅ iOS Keychain & Android Keystore backed
  • ❌ React Native/Expo only
  • ❌ Limited storage capacity (varies by platform)
  • ❌ Slower than in-memory cache

Example

import { ExpoSecureCache } from '@geekmidas/cache/expo';

interface AuthTokens {
  accessToken: string;
  refreshToken: string;
}

const cache = new ExpoSecureCache<AuthTokens>();

// Store tokens securely with 1 hour TTL
await cache.set('auth:tokens', {
  accessToken: 'eyJhbGciOiJIUzI1NiIs...',
  refreshToken: 'dGhpcyBpcyBhIHJlZnJlc2ggdG9rZW4...'
}, 3600);

// Retrieve tokens
const tokens = await cache.get('auth:tokens');

// Clear tokens on logout
await cache.delete('auth:tokens');

Platform Considerations

  • iOS: Uses Keychain Services, data persists across app reinstalls
  • Android: Uses Android Keystore, data cleared on app uninstall
  • Storage Limits: Approximately 2KB per item on most devices
  • Performance: Async operations can be slower than memory cache

Advanced Usage

Type Safety

The cache is fully type-safe with TypeScript generics:

// String cache
const stringCache = new InMemoryCache<string>();
await stringCache.set('key', 'value');
const str: string | undefined = await stringCache.get('key');

// Object cache
interface Product {
  id: number;
  name: string;
  price: number;
}

const productCache = new InMemoryCache<Product>();
await productCache.set('product:1', { id: 1, name: 'Widget', price: 9.99 });
const product: Product | undefined = await productCache.get('product:1');

Cache Abstraction

Create cache-agnostic services:

interface UserService {
  getUser(id: number): Promise<User | undefined>;
  setUser(user: User): Promise<void>;
  deleteUser(id: number): Promise<void>;
}

class CachedUserService implements UserService {
  constructor(
    private cache: Cache<User>,
    private userRepository: UserRepository
  ) {}

  async getUser(id: number): Promise<User | undefined> {
    const cacheKey = `user:${id}`;
    
    // Try cache first
    let user = await this.cache.get(cacheKey);
    if (user) return user;
    
    // Fallback to repository
    user = await this.userRepository.findById(id);
    if (user) {
      await this.cache.set(cacheKey, user, 3600); // 1 hour
    }
    
    return user;
  }

  async setUser(user: User): Promise<void> {
    await this.userRepository.save(user);
    await this.cache.set(`user:${user.id}`, user, 3600);
  }

  async deleteUser(id: number): Promise<void> {
    await this.userRepository.delete(id);
    await this.cache.delete(`user:${id}`);
  }
}

// Use with any cache implementation
const service = new CachedUserService(
  new InMemoryCache<User>(), // or new UpstashCache<User>(url, token)
  new UserRepository()
);

Factory Pattern

Create cache instances based on configuration:

interface CacheConfig {
  type: 'memory' | 'redis' | 'file' | 'expo';
  redis?: {
    url: string;
    token: string;
  };
  file?: {
    path?: string;
    ttl?: number;
  };
}

function createCache<T>(config: CacheConfig): Cache<T> {
  switch (config.type) {
    case 'memory':
      return new InMemoryCache<T>();
    case 'redis':
      if (!config.redis) throw new Error('Redis config required');
      return new UpstashCache<T>(config.redis.url, config.redis.token);
    case 'file':
      return new FileCache(config.file);
    case 'expo':
      return new ExpoSecureCache<T>();
    default:
      throw new Error(`Unsupported cache type: ${config.type}`);
  }
}

const cache = createCache<User>({
  type: process.env.NODE_ENV === 'production' ? 'redis' : 'memory',
  redis: {
    url: process.env.UPSTASH_REDIS_URL!,
    token: process.env.UPSTASH_REDIS_TOKEN!,
  },
});

Wrapper Pattern

Add functionality like logging or metrics:

class LoggingCache<T> implements Cache<T> {
  constructor(
    private cache: Cache<T>,
    private logger: Logger
  ) {}

  async get(key: string): Promise<T | undefined> {
    this.logger.debug(`Cache GET: ${key}`);
    const value = await this.cache.get(key);
    this.logger.debug(`Cache GET result: ${value ? 'HIT' : 'MISS'}`);
    return value;
  }

  async set(key: string, value: T, ttl?: number): Promise<void> {
    this.logger.debug(`Cache SET: ${key} (TTL: ${ttl})`);
    await this.cache.set(key, value, ttl);
  }

  async delete(key: string): Promise<void> {
    this.logger.debug(`Cache DELETE: ${key}`);
    await this.cache.delete(key);
  }
}

const cache = new LoggingCache(
  new UpstashCache<User>(url, token),
  logger
);

Testing

Mocking

The interface makes testing easy:

import { Cache } from '@geekmidas/cache';

class MockCache<T> implements Cache<T> {
  private store = new Map<string, T>();

  async get(key: string): Promise<T | undefined> {
    return this.store.get(key);
  }

  async set(key: string, value: T): Promise<void> {
    this.store.set(key, value);
  }

  async delete(key: string): Promise<void> {
    this.store.delete(key);
  }
}

// Use in tests
const mockCache = new MockCache<User>();
const service = new CachedUserService(mockCache, mockRepository);

Testing with Real Implementations

import { InMemoryCache } from '@geekmidas/cache/memory';

describe('UserService', () => {
  let cache: Cache<User>;
  let service: CachedUserService;

  beforeEach(() => {
    cache = new InMemoryCache<User>();
    service = new CachedUserService(cache, mockRepository);
  });

  it('should cache user data', async () => {
    const user = { id: 1, name: 'John' };
    await service.setUser(user);
    
    const cachedUser = await cache.get('user:1');
    expect(cachedUser).toEqual(user);
  });
});

Performance Considerations

InMemoryCache

  • Pros: Very fast, no network latency
  • Cons: Limited by available memory, not persistent
  • Best for: Development, testing, single-instance apps

UpstashCache

  • Pros: Persistent, distributed, scalable
  • Cons: Network latency, external dependency
  • Best for: Production, multi-instance apps, shared cache

FileCache

  • Pros: Persistent, no external services, cross-process safe
  • Cons: Disk I/O latency, not suitable for high throughput
  • Best for: CLI tools, build systems, local development caching

ExpoSecureCache

  • Pros: Secure, encrypted, persistent on device
  • Cons: React Native only, storage limits, slower operations
  • Best for: Mobile apps, sensitive data (tokens, credentials)

Key Strategies

  1. Use appropriate TTL: Balance between cache freshness and performance
  2. Consider cache size: Monitor memory usage for in-memory cache
  3. Implement fallback: Always have a fallback when cache is unavailable
  4. Use compression: For large objects, consider compression before caching

Error Handling

Cache operations can fail, so implement proper error handling:

async function getUserSafely(id: number): Promise<User | undefined> {
  try {
    const cached = await cache.get(`user:${id}`);
    if (cached) return cached;
  } catch (error) {
    console.warn('Cache get failed, falling back to database:', error);
  }

  try {
    const user = await database.getUser(id);
    if (user) {
      try {
        await cache.set(`user:${id}`, user, 3600);
      } catch (error) {
        console.warn('Cache set failed:', error);
      }
    }
    return user;
  } catch (error) {
    console.error('Database query failed:', error);
    throw error;
  }
}

Migration Guide

From Map to Cache

// Old way
const cache = new Map<string, User>();
cache.set('user:1', user);
const user = cache.get('user:1');

// New way
const cache = new InMemoryCache<User>();
await cache.set('user:1', user);
const user = await cache.get('user:1');

From Other Cache Libraries

Most cache libraries can be adapted to implement the Cache<T> interface:

class RedisCache<T> implements Cache<T> {
  constructor(private redis: RedisClient) {}

  async get(key: string): Promise<T | undefined> {
    const value = await this.redis.get(key);
    return value ? JSON.parse(value) : undefined;
  }

  async set(key: string, value: T, ttl?: number): Promise<void> {
    const serialized = JSON.stringify(value);
    if (ttl) {
      await this.redis.setex(key, ttl, serialized);
    } else {
      await this.redis.set(key, serialized);
    }
  }

  async delete(key: string): Promise<void> {
    await this.redis.del(key);
  }
}

Contributing

  1. Follow the existing code style (2 spaces, single quotes, semicolons)
  2. Add comprehensive tests for new features
  3. Ensure all implementations follow the Cache<T> interface
  4. Update documentation for API changes
  5. Use the "Integration over Unit" testing philosophy

License

MIT License - see the LICENSE file for details.

版本与发布记录

@geekmidas/cache 共发布 207 个版本,首次发布于 2025/07/14;过去 12 个月发布了 200 个版本。最新版本附带 npm provenance 构建来源证明,可追溯到公开的 CI 构建记录。

版本发布日期距今
9.6.1latest2026/11/16今天
10.0.0-alpha.185alpha2026/11/16今天
10.0.0-alpha.1842026/11/16今天
10.0.0-alpha.1832026/11/16今天
10.0.0-alpha.1822026/11/132 天前
10.0.0-alpha.1812026/11/133 天前

关于 @geekmidas/cache 的常见问题

@geekmidas/cache 是什么?

Unified cache interface with multiple storage implementations

如何安装 @geekmidas/cache?

在项目目录运行 npm install @geekmidas/cache,或使用 pnpm add / yarn add / bun add。它还需要宿主项目提供 peer 依赖:@upstash/redis(~1.35.1)、expo-secure-store(^14.2.3)。npm 7 及以上与 pnpm 8 及以上默认会自动安装必需的 peer 依赖,Yarn 需要手动安装。

@geekmidas/cache 支持 TypeScript 吗?

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

@geekmidas/cache 支持 ESM 还是 CommonJS?

同时提供 ES Module 与 CommonJS 入口,import 和 require() 都可以使用,打包工具会自动选择合适的版本。

@geekmidas/cache 可以商用吗?

@geekmidas/cache 使用 未声明 许可。package.json 没有声明许可证。没有许可证的代码默认保留全部权利,商用前请联系作者或查看仓库中的 LICENSE 文件。以上为概括,不构成法律意见,请以许可原文为准。

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

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

@geekmidas/cache 还在维护吗?

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