Skip to content

Folders and files

NameName
Last commit message
Last commit date

Latest commit

Β 

History

7 Commits
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 

Repository files navigation

cache-plus

A lightweight, generic caching library for TypeScript and Node.js.

cache-plus provides a simple and extensible caching abstraction with a built-in in-memory implementation. It is designed to be small, fast, and easy to integrate into applications while allowing other cache providers (Redis, Memcached, etc.) to implement the same interface.

Features

  • πŸš€ Lightweight with zero dependencies
  • πŸ”’ Generic CachePort interface
  • πŸ’Ύ Built-in in-memory cache
  • ⏱️ Optional TTL (Time-To-Live) support
  • πŸ“ Configurable memory limit
  • πŸ“¦ Automatic memory usage tracking
  • πŸ—‘οΈ Remove expired entries automatically on access
  • πŸ”Œ Easy to implement custom cache providers

Installation

npm install cache-plus

Quick Start

import { MemoryCacheService } from "cache-plus";

const cache = new MemoryCacheService<string>();

await cache.put("message", "Hello World");

const value = await cache.get("message");

console.log(value);

Store Objects

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

const cache = new MemoryCacheService<User>();

await cache.put("u1", {
  id: "u1",
  name: "John"
});

const user = await cache.get("u1");

Objects are automatically serialized and deserialized using JSON.


Store Raw Strings

const cache = new MemoryCacheService<string>(
  64,     // memory size (MB)
  false   // disable JSON serialization
);

await cache.put("token", "abc123");

Time-To-Live (TTL)

Store data that expires automatically.

await cache.put(
    "session",
    session,
    300 // seconds
);

Update the expiration time later.

await cache.expire("session", 600);

Check Existence

const exists = await cache.containsKey("user");

Remove Data

await cache.remove("user");

Clear the entire cache.

await cache.clear();

Multiple Keys

const users = await cache.getMany([
    "u1",
    "u2",
    "u3"
]);

Cache Information

const count = await cache.count();

const bytes = await cache.size();

const keys = await cache.keys();

CachePort Interface

export interface CachePort<K, V> {
    isEnabled?(): boolean;

    put(key: K, obj: V, expiresInSeconds?: number): Promise<boolean>;

    expire(key: K, timeToLive: number): Promise<boolean>;

    get(key: K): Promise<V>;

    getMany(keys: K[]): Promise<V[]>;

    containsKey(key: K): Promise<boolean>;

    remove(key: K): Promise<boolean>;

    clear(): Promise<boolean>;

    keys(): Promise<string[]>;

    count(): Promise<number>;

    size(): Promise<number>;
}

This interface allows applications to switch cache implementations without changing business logic.


Memory Cache

The package includes an in-memory implementation.

const cache = new MemoryCacheService<User>();

Constructor

new MemoryCacheService(
    memorySizeMB = 64,
    json = true,
    enabled = true
)
Parameter Description
memorySizeMB Maximum memory size in MB
json Automatically serialize objects
enabled Enable or disable caching

Memory Management

cache-plus keeps track of memory usage using UTF-8 byte size.

When the configured memory limit is exceeded, the oldest entries are automatically removed until the cache size falls below the limit.

This allows the cache to operate within a fixed memory budget.


Expiration

Expiration is evaluated lazily.

Expired entries are removed automatically when they are accessed or when cache metadata is queried.

This approach avoids background timers and minimizes CPU usage.


Implement Your Own Cache

You can implement your own cache provider by implementing the CachePort interface.

Example:

class RedisCacheService<T>
    implements CachePort<string, T> {

    async put(key: string, value: T): Promise<boolean> {
        ...
    }

    async get(key: string): Promise<T> {
        ...
    }

    ...
}

Applications can then switch implementations without changing business logic.


Why cache-plus?

Unlike many cache libraries that are tightly coupled to a specific storage engine, cache-plus focuses on providing a clean abstraction.

  • Memory cache
  • Redis
  • Memcached
  • Distributed cache
  • Custom cache implementations

can all share the same API.

This makes applications easier to test, maintain, and extend.


Use Cases

  • Application caching
  • Session caching
  • API response caching
  • Configuration caching
  • Reference data caching
  • Authentication tokens
  • Feature flags
  • Rate limiting support
  • Temporary objects

Requirements

  • Node.js 16+
  • TypeScript 5+

License

MIT

About

No description, website, or topics provided.

Resources

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Used by

Contributors

Languages