Creates a local cache. If a value does not exist in cache it using the producer function to get it.
const cachedProducer = require('kiss-cached-producer')
const db = require('a-database-api')
const productGetter = cachedProducer(
productId => {
// Got get something from database
db.getProduct(productId)
}
)
const product1 = productGetter(123) // First time will goto the database
const product2 = productGetter(123) // This time will resolve from cache
Sometimes you need to pass a state into the calling function ...
const cachedProducer = require('kiss-cached-producer')
const db = require('a-database-api')
const productGetter = cachedProducer(
(productId, state) => {
// Got get something from database
state.getProduct(productId)
},
db, // This is the program state
)
const product1 = productGetter(123) // First time will goto the database
const product2 = productGetter(123) // This time will resolve from cache
Sometimes you need to extract the key value from an object...
const cachedProducer = require('kiss-cached-producer')
const db = require('a-database-api')
const productGetter = cachedProducer(
(productId, state) => {
// Got get something from database
state.getProduct(productId)
},
db, // This is the program state
o => o.productId // A getter function to return the cache key value
)
const product1 = productGetter({productId:123}) // First time will goto the database
const product2 = productGetter({productId:123}) // This time will resolve from cache