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

cached-promise

v1.0.0

Published

Take LRU-cache, add a little Promises, stir vigorously, let simmer, enjoy!

Downloads

1,340

Readme

Cached Promise Build Status

NPM

Take LRU-cache, add a little Promises, stir vigorously, let simmer, enjoy!

Install

npm install cached-promise

Use

var CachedPromise = require('cached-promise');

var people = new CachedPromise({
  maxAge: 1000 * 2,
  load: function (data, resolve, reject) {
    process.nextTick(function () { // simulated async call
      resolve({
        datetime: new Date().getTime(),
        key: data.key // <- "bob"
      });
    });
  }
});

setInterval(function () {

  people.get('bob')
    .then(function(result) {
      // do something with the result
    })
    .catch(function (err) {
      throw new Error(err);
    });

}, 900);

Keys as objects

I found that I often needed to have other bits of data available in my load() function besides just the key so I modified the API to be able to handle objects as the key.

var CachedPromise = require('cached-promise');

var people = new CachedPromise({
  maxAge: 1000 * 2,
  load: function (data, resolve, reject) {
    process.nextTick(function () { // simulated async call
      resolve({
        datetime: new Date().getTime(),
        key: data.key, // <- "bob"
        email: data.email // <- "[email protected]"
      });
    });
  }
});
setTimeout(function() {

  people.get({
    key: 'bob',
    email: '[email protected]'
  })
    .then(function(result) {
      // do something with the result
    })
    .catch(function(err) {
      throw new Error(err);
    })

}, 1000);

new CachedPromise(options)

Cached Promise relies on LRU cache to do the heavy lifting for caching. As such, the options are passed through with one exception:

load(key, resolve, reject)

The load option is the async call that you want to make that produces the value to cache. You can still manually .set(key, value) items in the cache, but the load() call will auto-populate/refresh the cache.

Say, for example, that you wanted to make a RESTful API call and cache the result for 30 seconds:

var CachedPromise = require('cached-promise'),
    request = require('request');

var users = new CachedPromise({
  maxAge: 1000 * 30,
  load: function (key, resolve, reject) {
    request({
      method: 'get',
      url: 'http://localhost:8080/api/users/' + key,
      json: true
    }, function(err, res, json) {
      if (err)
        return reject(err);
      resolve(json);
    });
  }
});

setInterval(function () {

  users.get('bob')
    .then(function(result) {
      // do something with the result
    })
    .catch(function (err) {
      throw new Error(err);
    });

}, 1000);

In this example, the first time you call users.get('bob'), Cached Promise will execute load() and return the result when the request is complete.

The value will then be cached for 30 seconds and subsequent calls to users.get('bob') will hit the cache instead of making a call to the RESTful API.

cache.set(key, value)

Cached Promise also allows you to manually set cache items just like you can with LRU cache, it just wraps the standard LRU .set(key, value) method with a promise.

Other LRU methods

Cached Promise wraps all other LRU methods with a simple promise to keep things uniform.

LRU .forEach()

This one is NOT promise-wrapper. If you call cache.forEach() it will be passed through directly to the LRU forEach() method.

// example taken from the tests
//
var item = {
  datetime: new Date()
};

cache.set('foo', item) // manually create the item
  .then(function (values) {
    cache.forEach(function(value, key, _cache) {
      (value.datetime).should.equal(item.datetime);
      (key).should.equal('foo');
      (_cache).should.be.an.instanceof(LRU);
    });
  });

Test

npm test

Versions

  • 1.0.0 Refactored to ES6 and introduced pending handler
    • Pending handler will hold all load() calls for the same key until the first one is resolved.
  • 0.1.1 Added feature to allow using objects with key property as the key
  • 0.0.1 Initial version