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

0.0.4 • Public • Published

multi-layers-cache

A very simple multi layers cache.

Usage

import { newCacheStorage, newLRUCache } from 'multi-layers-cache';

const cache = newCacheStorage({ layers: [newLRUCache()] });
await cache.set('ah', 10);
console.log(await cache.get('ah'));

newLRUCache will create a simple in-memory LRU cache using Map.

You can build your own cache, with just simple interfaces:

interface Cache {
  get(key: string): Promise<Value | undefined>;
  /**
   * @param expireAt In seconds
   */
  set(key: string, value: string | number, expireAt?: number): Promise<void>;
  del(key: string): Promise<void>;
}

interface Value {
  expireAt: number;
  value: string | number;
  key: string;
}

Redis cache layer

import { Redis } from 'ioredis'

interface Cache {
  get(key: string): Promise<Value | undefined>
  /**
   * @param expireAt In seconds
   */
  set(key: string, value: string | number, expireAt?: number): Promise<void>
  del(key: string): Promise<void>
}

interface Value {
  /**
   * `-1` means No expiration.
   */
  expireAt: number
  value: string | number
  key: string
}

export function newRedisCache(): Cache {
  const redis = new Redis()
  return {
    async get(key) {
      const results = await redis.pipeline().get(key).ttl(key).exec()

      if (!results) {
        return
      }

      const [[, value], [, ttl]] = results
      return {
        value: value as string,
        key,
        expireAt: ttl as number,
      }
    },
    async set(key, value, expireAt) {
      expireAt ? await redis.setex(key, expireAt, value) : await redis.set(key, value)
    },
    async del(key) {
      await redis.del(key)
    },
  }
}

Usage with redis cache

import { newCacheStorage, newLRUCache } from 'multi-layers-cache';

const cache = newCacheStorage({ layers: [newLRUCache(), newRedisCache()] });
await cache.set('ah', 'hello', 10 /* 10 seconds */);
console.log(await cache.get('ah'));

How it works?

newCacheStorage returns a Cache compatible instance.

It maintains an internal array of cache layers. When a get operation is performed, it loops through the cache layers sequentially. If it finds a value on a higher layer, it saves that value to the lower layers with the same ttl. For set and del operations, items are modified or removed in all layers.

LICENSE

BSD-3-Clause @ Ninh Pham (ReeganExE)

Package Sidebar

Install

npm i multi-layers-cache

Weekly Downloads

1

Version

0.0.4

License

BSD-3-Clause

Unpacked Size

10.6 kB

Total Files

8

Last publish

Collaborators

  • reeganexe