npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

tkv-cache

v1.0.1

Published

A simple TypeScript Keyv cache

Downloads

786

Readme

TypeScript KvCache

Build Status npm version

Minimal Keyv powered caching helper with added support for:

  • Objects as keys with key ordering and hashing
  • Function to normalize keys to optimize cache hit rate
  • Helper function for wrapping functions with caching
  • Strongly typed set/get with generic types

All storage is handled by the Keyv instance passed, so you can use the in-memory default, or any of the storage adapters.

Usage

Install

Install tkv-cache with your favorite package manager: npm, yarn, pnpm, etc.

You also need to install keyv and any adapters like @keyv/redis.

KvCache

The KvCache class wraps Keyv with support for object keys and key normalization.

import Keyv from 'keyv';
import { KvCache } from 'tkv-cache';

// Simple usage
const cache = new KvCache<string, string>(new Keyv());
await cache.set('key', 'value');
const val = await cache.get('key'); // val is: string | null

// Object as the key
type ObjKey = { name: string };
const cache2 = new KvCache<ObjKey, string>(new Keyv());
await cache2.set({ name: 'key1' }, 'value');
const val2 = await cache2.get({ name: 'key1' }); // val2 is: string | null

// With a custom normalizeKey function
const cache3 = new KvCache<string, string>(
  new Keyv(),
  (key) => key.toUpperCase()
);
await cache3.set('key', 'value');
const val3 = await cache3.get('KEY'); // val3 is: string | null
console.log(val3); // 'value' because keys were normalized to 'KEY'

Easy KvCache Creation

You can create a KVCache instance using the createKvCache() function by passing in a Keyv options object.

const cache = createKvCache<string, string>({
  ttl: 1000,
});
await cache.set('key', 'value');
const val = await cache.get('key');
type verify = Expect<Equal<typeof val, string | null>>;
assert.equal(val, 'value');

Cachify

The cachify function wraps a function with a KvCache and optional key normalization function.

import Keyv from 'keyv';
import { cachify } from 'tkv-cache';

// The function to cache. Something slow/expensive like an OpenAI API call.
const func = (key: string) => Promise.resolve(`value for ${key}`);

// The cached function
const cachedFunc = cachify({}, func);

const response = await cachedFunc('key1'); // API call
const response2 = await cachedFunc('key1'); // Cache hit
const response3 = await cachedFunc('key2'); // API call

// Use key normalization to avoid cache misses
const cachedFunc2 = cachify(new Keyv(), func, (key) => key.toUpperCase());

const res = await cachedFunc('key1'); // API call
const res2 = await cachedFunc('key1'); // Cache hit
const res3 = await cachedFunc('KEY1'); // Cache hit (key normalization)
const res4 = await cachedFunc('Key1'); // Cache hit (key normalization)
const res5 = await cachedFunc('key2'); // API call

Error Handling

KvCache defaults to handling errors by calling console.error to prevent caching from breaking execution. You can pass a custom error handler to the KvCache constructor if you want to change the behavior.

Examples

See the KvCache tests and cachify tests for more example usage.