Skip to content

SuperphonicHub/key-value-lru-file-cache

Repository files navigation

key-value-lru-file-cache

npm package Build Status Downloads Issues Code Coverage Commitizen Friendly Semantic Release


Superphonic Logo

This package is used by: Superphonic

Install

npm install key-value-lru-file-cache

or

yarn add key-value-lru-file-cache

Example

import { getCache } from "key-value-lru-file-cache";
import MMKV from "react-native-mmkv";
import ReactNativeBlobUtil from "react-native-blob-util";

// Example key parameters type (or just use a primitive)
interface ImageCacheKey {
  remoteImgPath: string;
  width: number;
  height: number;
}

// Create the cache instance
const imageCache = getCache({
  prefix: "IMG_RESIZED",
  evictionMillis: 7 * 24 * 60 * 60 * 1000, // 1 week
  maxEntries: 1000,
  maxCacheSize: 300 * 1024 * 1024, // 300MB

  // Key/value storage using MMKV
  getValue: async key => MMKV.getString(key) ?? null,
  setValue: async (key, value) => {
    try {
      MMKV.set(key, value);
      return true;
    } catch {
      return false;
    }
  },
  delete: async key => {
    try {
      MMKV.delete(key);
      return true;
    } catch {
      return false;
    }
  },
  getAllKeys: async () => MMKV.getAllKeys(),
  getKeyFor: async params => {
    const encodedUri = encodeURIComponent(params.remoteImgPath);
    return `IMG_RESIZED:${encodedUri}-${params.width}-${params.height}`;
  },

  // File system operations using react-native-blob-util
  fileExists: path => ReactNativeBlobUtil.fs.exists(path),
  fileUnlink: async path => {
    try {
      await ReactNativeBlobUtil.fs.unlink(path);
      return true;
    } catch {
      return false;
    }
  },
  fileSize: async path => {
    const stat = await ReactNativeBlobUtil.fs.stat(path);
    return stat.size;
  },
});

// Using the cache
async function exampleUsage() {
  // Put a file in cache
  await imageCache.put(
    {
      remoteImgPath: "https://example.com/image.jpg",
      width: 200,
      height: 200,
    },
    "/local/path/to/resized-image.jpg"
  );

  // Get a file from cache
  const filePath = await imageCache.get({
    remoteImgPath: "https://example.com/image.jpg",
    width: 200,
    height: 200,
  });

  if (filePath) {
    console.log("Found cached file:", filePath);
  } else {
    console.log("File not in cache or expired");
  }

  // Clean expired entries
  await imageCache.cleanExpiredEntries();
}

API

KeyValueCache<TKeyParams>

A generic, adapter‑based key‑value + file LRU cache with eviction based on:

  • Max age (evictionMillis)
  • Max entries (maxEntries)
  • Max total disk size (maxCacheSize)

Constructor

new KeyValueCache<TKeyParams>(adapter: KeyValueCacheAdapter<TKeyParams>)

Parameters:

Parameter Type Description
adapter KeyValueCacheAdapter<TKeyParams> Implementation of the key‑value and file system adapter methods required by the cache.

Adapter Interface: KeyValueCacheAdapter<TKeyParams>

Property / Method Type Description
prefix string Prefix for all keys in the cache.
evictionMillis number Max age (in milliseconds) before an entry expires.
maxEntries number Maximum number of entries allowed in the cache.
maxCacheSize number Maximum total cache size in bytes.
getValueForKey(key) (key: string) => Promise<string | null> Get value for a given key.
setValueForKey(key, value) (key: string, value: string) => Promise<boolean> Store value for a given key.
deleteKeyValue(key) (key: string) => Promise<boolean> Delete a key/value pair.
getAllKeys() () => Promise<string[]> Get all keys from the store.
getKeyFor(params) (params: TKeyParams) => Promise<string | null> Build a unique key string from parameters.
fileExists(path) (path: string) => Promise<boolean> Check if a file exists at the given path.
fileUnlink(path) (path: string) => Promise<boolean> Delete a file at the given path.
fileSize(path) (path: string) => Promise<number> Get file size in bytes.

Instance Methods

Method Returns Description
get(params) Promise<string | null> Get file path for given params if entry exists and is valid. Updates lastAccessed on hit.
put(params, filePath) Promise<boolean> Add/update an entry in the cache. Triggers eviction if limits exceeded.
delete(params) Promise<boolean> Remove an entry and delete its file if present.
cleanExpiredEntries() Promise<boolean> Remove all entries older than evictionMillis. Returns true if any were removed.
getCurrentEntriesCount() Promise<number> Get current number of cached entries.
getCurrentDiskSize() Promise<number> Get current total cache size in bytes.

About

No description, website, or topics provided.

Resources

License

Stars

Watchers

Forks

Packages

No packages published

Contributors 6