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

@patoi/oss-cache

v1.1.2

Published

Node.js memory cache with TTL

Downloads

6

Readme

Zero dependency Node.js memory cache with TTL

oss-cache can handle multiple caches.

Install: npm i @patoi/oss-cache

Using

import Caches from '@patoi/oss-cache'

// creating a cache
await Caches.create({
  name: 'cacheTest',
  ttl: 5555,
  asyncLoadFunction: async function () {
    let _map = new Map()
    _map.set('key', 'value')
    return _map
  },
  // optional
  logEmitter
})

// using cacheTest cache
const cacheTest = Caches.get('cacheTest')
const value = cacheTest.get('key')

// destroy a specific cache
Caches.destroy('cacheTest)
// destroy all cache, call before process exit
Cache.destroyAll()
  • name: cache name
  • ttl (time-to-live): cache eviction time in millisecond, when it expires, the cache will be refreshed
  • asyncLoadFunction: cache data loader, async function, must return a JavaScript Map object
  • logEmmiter: optional, listener of the cache log events

Other features

Programmatically triggered cache refresh

await cacheTest.refresh()

Reading outdated cache: you may get old data, so it is not safe.

const cacheValue = cacheTest.getUnsafe(key)
// value of the key
console.log(cacheValue.value)
// isOutdated boolean, if true, then the data is outdated
console.log(cacheValue.isOutdated)

The cache may become stale if the asyncLoadFunction throws an error, or if the cache is being destroyed.

If the cache reaches its TTL time and is refreshed again, the result of running asyncLoadFunction will be whether the cache is stale or not.

Best practices

  1. Guard cache: check if the cache exists before using it.
// using cacheTest cache
const cacheTest = Caches.get('cacheTest')
if (!cacheTest) throw new Error('Missing cache!')
const value = cacheTest.get('key')
  1. Guard cache value: check the returned value.
const value = cacheTest.get('unknown_key')
if (value === undefined) { // handling undefined value }
  1. Guard outdated cache
try {
  // outdated cache reading throws an error
  const value = cacheTest.get(key)
} catch (error) {
  // error.message: 'Cache is outdated.'
  // error.code: 'ERR_CACHE_OUT_OF_DATE'
}

You can use getUnsafe(key) method, it doesn't throw error if cache is outdated.

  // outdated cache reading doesn't throw an error
  const cacheValue = cacheTest.getUnsafe(key)
  // if you want to handling fresh or outdated cases...
  if (cacheValue.isOutdated) {
    console.log('Outdated value:', cacheValue.value)
  } else {
    console.log('Fresh value:', cacheValue.value)
  }
}
  1. Logging cache events, highly recommended: 'cache:log:warn' event
import { EventEmitter } from 'node:events'
import Caches from './lib/index.js'

// cache events logger
const logEmitter = new EventEmitter()

// cache warn event, for example: cache is outdated.
logEmitter.on('cache:log:warn', (name, message) =>
  console.log('Cache log warning', { name, message })
)

// cache data loading has started
logEmitter.on('cache:log:init:start', name =>
  console.log('Cache init started', { name })
)

// cache data loaded: runtime is the time of running of your cache initialization function (asyncLoadFunction)
logEmitter.on('cache:log:init:end', (name, runtime) =>
  console.log('Cache init end', { name, runtime })
)

// cache load event details
logEmitter.on(
  'cache:log:load',
  (name, count, isForcedReload, lastLoadTimestamp, isExpired) => {
    console.log('map refreshed: ', {
      name,
      count,
      isForcedReload,
      lastLoadTimestamp,
      isExpired
    })
    if (isExpired) {
      console.log('Cache expired, refresh')
    }
    if (isForcedReload) {
      console.log('Cache explicit reload, refresh() called')
    }
  }
)

// programmatically forced cache refresh event
logEmitter.on('cache:log:refresh', (name, count, lastLoadTimestamp) =>
  console.log('Cache refresh', { name, count, lastLoadTimestamp })
)

// cache read by get()
logEmitter.on('cache:log:get', (name, key, value) =>
  console.log('get()', { name, key, value })
)

// cache read by getUnsafe()
logEmitter.on('cache:log:getUnsafe', (name, key, value) =>
  console.log('getUnsafe()', { name, key, value })
)
  1. Checkout example.js and index.spec.js for detailed using information.

  2. You can run example wit node example.js or test pnpm i && pnpm test