hapi icon indicating copy to clipboard operation
hapi copied to clipboard

Using cache in plugin.register directly will ignore cache load for the first time

Open petermilan opened this issue 12 years ago • 1 comments

I've just tried to learn how to use the caching inside of the plugin, so I tried to call the cached method directly in the plugin.register function. I am just curious why everytime I started hapi server, my cached plugin method was ignoring the cache for the first time. But If I called the plugin.method inside of handler it worked properly. (the first call of the method was always hitting the remote service). here is example code:

exports.register = function(plugin, options , next) {

  internals.checkId = function(id, next) {
    var url = 'http://google.com';
    Nipple.get(url, function (err, res, payload) {
      console.log('Remote call');
      if (err) {
        next(err);
      } else {
        // TODO: handle service response
        next(null, true);
      }
    });
  };

  var SECOND = 1000;
  var MINUTE = 60 * SECOND;
  plugin.method('checkId', internals.checkId, {
    cache: {
      expiresIn: 60 * MINUTE
    }
  });

  var id = 'abc';
  plugin.methods.checkId(id, function(error, exists) {
    console.log(error, exists);
    plugin.methods.checkId(id, function(error, exists) {
      console.log(error, exists);
      plugin.methods.checkId(id, function(error, exists) {
        console.log(error, exists);
      });
    });
  });
  next();
};

and every time I will start the server I got this:

Remote call
null true
null true
null true

so every first call inside of plugin.register is ignoring the cache, and loading the data from external service. Inside of handler it is working properly.

petermilan avatar Jun 04 '14 12:06 petermilan

Because the cache is only started when the server starts.

hueniverse avatar Jun 09 '14 14:06 hueniverse