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

polycache-core

v1.0.1

Published

Cache module for Node.js

Downloads

19

Readme

polycache

codecov tests license npm npm

Flexible multi cache module

A cache module for node that allows easy wrapping of functions, tiered caches, and a consistent interface.

Features

  • Made with Typescript and compatible with ESModules
  • Easy way to wrap any function in cache.
  • Tiered caches -- data gets stored in each cache and fetched from the highest priority cache(s) first.
  • Use any cache you want, as long as it has the same API.
  • 100% test coverage via vitest.

Installation

npm install polycache-core

Usage Examples

Single Store

import { caching, createLruStore } from 'polycache-core';

const memoryCache = caching(
  createLruStore({
    max: 100,
    ttl: 10 * 1000 /*milliseconds*/,
  }),
);

const ttl = 5 * 1000; /*milliseconds*/
await memoryCache.set('foo', 'bar', ttl);

console.log(await memoryCache.get('foo'));
// >> "bar"

await memoryCache.del('foo');

console.log(await memoryCache.get('foo'));
// >> undefined

const getUser = (id: string) => new Promise.resolve({ id: id, name: 'Bob' });

const userId = 123;
const key = 'user_' + userId;

console.log(await memoryCache.wrap(key, () => getUser(userId), ttl));
// >> { id: 123, name: 'Bob' }

Example setting/getting several keys with setMany() and getMany()

await memoryCache.store.setMany(
  [
    ['foo', 'bar'],
    ['foo2', 'bar2'],
  ],
  ttl,
);

console.log(await memoryCache.store.getMany('foo', 'foo2'));
// >> ['bar', 'bar2']

// Delete keys with delMany() passing arguments...
await memoryCache.store.delMany('foo', 'foo2');

Custom Stores

Custom stores can be easily built by adhering to the Store type.

Multi-Store

import { multiCaching } from 'polycache-core';

const multiCache = multiCaching([memoryCache, someOtherCache]);
const userId2 = 456;
const key2 = 'user_' + userId;
const ttl = 5;

// Sets in all caches.
await multiCache.set('foo2', 'bar2', ttl);

// Fetches from highest priority cache that has the key.
console.log(await multiCache.get('foo2'));
// >> "bar2"

// Delete from all caches
await multiCache.del('foo2');

// Sets multiple keys in all caches.
// You can pass as many key, value tuples as you want
await multiCache.setMany(
  [
    ['foo', 'bar'],
    ['foo2', 'bar2'],
  ],
  ttl,
);

// getMany() fetches from highest priority cache.
// If the first cache does not return all the keys,
// the next cache is fetched with the keys that were not found.
// This is done recursively until either:
// - all have been found
// - all caches has been fetched
console.log(await multiCache.getMany('key', 'key2'));
// >> ['bar', 'bar2']

// Delete keys with delMany() passing arguments...
await multiCache.delMany('foo', 'foo2');

Refresh cache keys in background

Both the caching and multicaching modules support a mechanism to refresh expiring cache keys in background when using the wrap function.
This is done by adding a refreshThreshold attribute while creating the caching store.

If refreshThreshold is set and after retrieving a value from cache the TTL will be checked.
If the remaining TTL is less than refreshThreshold, the system will update the value asynchronously,
following same rules as standard fetching. In the meantime, the system will return the old value until expiration.

NOTES:

  • In case of multicaching, the store that will be checked for refresh is the one where the key will be found first (highest priority).
  • If the threshold is low and the worker function is slow, the key may expire and you may encounter a racing condition with updating values.
  • The background refresh mechanism currently does not support providing multiple keys to wrap function.
  • If no ttl is set for the key, the refresh mechanism will not be triggered. For redis, the ttl is set to -1 by default.

For example, pass the refreshThreshold to caching like this:

import { createLruStore, caching } from 'polycache-core';

const memoryCache = caching(
  createLruStore({
    max: 100,
    ttl: 10 * 1000 /*milliseconds*/,
  }),
  {
    refreshThreshold: 3 * 1000 /*milliseconds*/,
  },
);

When a value will be retrieved from Redis with a TTL minor than 3sec, the value will be updated in the background.

Store Engines

  • Built-in LRU store for in-memory caching.

Under construction...

Contribute

If you would like to contribute to the project, please fork it and send us a pull request. Please add tests for any new features or bug fixes.

License

polycache is licensed under the MIT license.