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

layered-cache

v4.0.2

Published

The manager to handle hierarchical cache layers.

Downloads

412

Readme

Build Status Coverage

layered-cache

The manager to handle hierarchical cache layers.

Usage

import LRU from 'lru-cache'
import LCache from 'layered-cache'

const cache = new LCache([
  // LRU cache
  new LRU({max: 100}),

  // databases
  {
    set: (key, value) => save_to_db(key, value),
    get: async key => await get_from_db(key)
  },

  // remote servers
  {
    get: key => fetch_from_remote(key)
  }
])

cache.get('foo')  // 'bar'

For the example above, at first, there was no cache for 'foo' either in LRU cache(layer 0), or in databases(layer 1). And LCache tries to fetch the value of 'foo' from remote server, and gets the value of 'bar'.

Then, LCache saves {foo: 'value'} to both layer 0 and layer 1.

If we try to get the value of 'foo' again, it will hit on layer 0. And after a long time, if the value of 'foo' have been erased by LRU cache, LCache will the the value from databases(layer 1).

To make the cache simple enough, ALL VALUES that equal to undefined or null are treated as NOT FOUND in the cache or cache layers. You could specify the behavior via options.isNotFound.

flow

class LCache(layers, options)

  • layers Array<LCache.InterfaceLayer|LCache.Layer> list of cache layers. A layer must implement the interface of LCache.InterfaceLayer. In the other words, a layer should have the following structures, but there is no restriction about which type the layer is. A layer could be a singleton(object), or a class instance(with properties from its prototype).
  • options Object=
    • isNotFound function(value): Boolean to determine whether a value is not found.

interface LCache.InterfaceLayer

  • get ?function(key: any): any method to get the cache, either synchronous or asynchronous(function that returns Promise or async function).
    • key any the key to retrieve the cached value could be of any type which layered-cache never concerns.
  • mget ?function(...keys): Array<any> an optional method to get multiple data by keys
  • set ?function(key, value: any) method to set the cache value, either sync or async. The method could be optional only for the last layer.
  • mset ?function(pairs: Array<[key: any, value: any]>) an optional method to set multiple values by keys.
  • has ?function(key) : Boolean an optional method to detect if a key is already in the cache, either sync or async.
  • mhas ?function(...keys) : Array<Boolean> an optional method to detect the existence of multiple keys, either sync or async.
  • validate ?function(key, value) : Boolean an optional method to validate the value and determine whether a value from a low-level cache should be saved.
  • mvalidate ?function(pairs: Array<[key: any, value: any]>) : Array<Boolean> an optional method to validate multiple key-value pairs and determine whether a value from a low-level cache should be saved.

At least one of get or mget must be specified, or it will throw an error.

cache.get(key)

  • key any the layered cache could accept arbitrary type of key

Gets a value by key, and returns Promise<any> the retrieved value.

Take lru-cache for example, which by default does not support arbitrary type of key, but we can use this simple trick:

import _LRU from 'lru-cache'

class LRU {
  constructor () {
    this._cache = new _LRU({
      max: 10000
    })
  }

  get (key) {
    return this._cache.get(JSON.stringify(key))
  }

  set (key, value) {
    return this._cache.set(JSON.stringify(key), value)
  }
}

cache.mget(...keys)

  • keys Array

Gets an group of values by keys, and returns Promise<Array>

cache.set(key, value)

Sets key-value to all writable cache layers.

Returns Promise

cache.mset(...pairs)

  • pairs Array<[key, value]>

Sets multiple key-value pairs.

Returns Promise

await cache.mset(['foo', 'bar'], ['baz', 'quux'])

cache.sync(key)

Synchronize the value of key from the most underlying layer up to the upper layers.

Returns the same data type as cache.get(key)

cache.msync(...keys)

Synchronize the value of each key from the most underlying layer up to the upper layers.

Returns the same data type as cache.mget(...keys)

cache.depth()

Returns number the depth of the cache layers.

cache.layer(n)

  • n number the index of the layer. The n starts with 0, from high level to low level, which means the layer index of the highest level is 0

Returns LCache.Layer

console.log(await cache.layer(0).get('foo'))

class LCache.Layer(layer: LCache.InterfaceLayer)

The wrapper class to wrap the cache layer, and always and only provides FOUR asynchronous methods, get, mget, set and mset.

import {
  Layer
} from 'layered-cache'
import delay from 'delay'

const store = {}
const layer = new Layer({
  get (x) {
    return delay(100).then(() => x + 1)
  },

  set (key, value) {
    store[key] = value
  },

  has (key) {
    return key in store
  }
})

layer.get(1).then(console.log)
// prints: on data 2
// prints: 2

License

MIT