2.0.2 • Published 7 years ago

litter-box v2.0.2

Weekly downloads
2
License
ISC
Repository
github
Last release
7 years ago

litter-box

A few function memoization helpers to work with catbox.

standard travis npm

Promise Memoization

litterBox.memoizeFnPromise(options)

Arguments

  • options: object. Required. An object with the following keys:
    • client: Catbox Client Instance. Required. A catbox client instance.
    • fn: Function. Required. A function which returns a Promise.
    • ttl: Integer. Required. The time-to-live for the cached fn result.
    • keyProvider: (fn-input) => {id, segment}. Required. A function which returns a cache-key for Catbox. This function is called with the same arguments as fn, allowing you to create a dynamic cache-key, for example:
  const exampleKeyProvider = (input) => ({ segment: 'test', id: `test-${input}` })

Promise Memoization Example:

This code is also available here.

const litterBox = require('litter-box')

const examplePromiseFunction = (input) => Promise.resolve(input)

const cachedPromiseFunction = litterBox.memoizeFnPromise({
  client: catboxClientInstance,
  fn: examplePromiseFunction,
  keyProvider: (input) => ({ segment: 'test', id: `test-${input}` }),
  ttl: 5 * 60 * 1000 // 5 minutes
})

cachedPromiseFunction(1234)
  .then(console.log) // prints 1234

// later on...
cachedPromiseFunction(1234) // function not executed, value is pulled from the cache
  .then((result) => { // returns 1234
    console.log(result)
    process.exit(0)
  })

Callback Memoization

litterBox.memoizeFnCallback(options)

Arguments

  • options: object. Required. An object with the following keys:
    • client: Catbox Client Instance. Required. A catbox client instance.
    • fn: Function. Required. A function which has a callback as it's final argument.
    • ttl: Integer. Required. The time-to-live for the cached fn result.
    • keyProvider: (fn-input) => {id, segment}. Required. A function which returns a cache-key for Catbox. This function is called with the same arguments as fn, allowing you to create a dynamic cache-key, for example:
  const exampleKeyProvider = (input) => ({ segment: 'test', id: `test-${input}` })

Callback Memoization Example:

This code is also available here.

const litterBox = require('litter-box')

const exampleCallbackFunction = (input, cb) => cb(null, input)

const cachedCallbackFunction = litterBox.memoizeFnPromise({
  client: catboxClientInstance,
  fn: exampleCallbackFunction,
  keyProvider: (input) => ({ segment: 'test', id: `test-${input}` }),
  ttl: 5 * 60 * 1000 // 5 minutes
})

cachedCallbackFunction(1234, (err, result) => console.log(result)) // prints 1234

// later on...

// function not executed, value is pulled from the cache
cachedCallbackFunction(1234, (err, result) => console.log(result)) // prints 1234

l