Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Added an initialiserFn parameter to the 'get' function. #132

Closed
wants to merge 4 commits into from

Conversation

nickgrealy
Copy link

Hi all,

I had a problem, trying to demultiplex a call chain, and realised I could solve it using the lru-cache with maxAge and promises - awesome!

To that end, I thought the library would benefit from having a get(key, initialiserFn) function, so that:

  • the existing get(key) signature would behave as per existing functionality
  • a user can specify an optional initialiser function, to populate the cached value (if not present)
  • the initialiser function may be an asynchronous/expensive operation/take a long time/be rate limited
  • in this way, the initialiser is invoked once, and it's response is cached for multiple calls
  • this works well, for initialiser functions that return a Promise
  • if maxAge is specified, the value would eventually be evicted

Here's an actual example I'm using it for (using socket.io):

server.js

// setup an LRU cache (with eviction policy)...
const PROFILE_CACHE = LRU({ max: 50, maxAge: 1000 * 60 })

// receives "lots" of async requests from a client...
socket.on('getUserProfileRequest', userId => {
  PROFILE_CACHE.get(userId, () => getUserProfile(userId))
    .then(profile => socket.emit('getUserProfileResponse', profile))
})

// calls upstream server, does async/expensive/long running work, returns a Promise...
function getUserProfile(userId) { /* ... */ }

@isaacs isaacs closed this Feb 8, 2022
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

None yet

2 participants