koa-prerender icon indicating copy to clipboard operation
koa-prerender copied to clipboard

Caching

Open mitom opened this issue 9 years ago • 0 comments

How would you go about caching while using this? The express middleware supports both plugins and has before and after calls to do any caching (or whatever else) necessary.

I have tried to wrap the middleware in an other one to handle caching but just hit a wall with needing to decide whether to load the cache or not. It works quite well for saving the result, however I am unsure about the this.response.is('html') as a sole source to tell whether it was pre-rendered or not. I looked into the code but the major part of this library is deciding whether to prerender or not, so duplicating that seems like a bad solution. Would you be open to adding an option say beforePrerender that would take a generator and yield to it only if prerendering is going to happen? It would also make it more consistent to add an afterPrerender one, but that wouldn't make that big of a difference apart from being able to tell for sure whether or not prerendering happened (since it would only get called if it did).

The code I used is below, if you have a better idea to decide whether to actually look for the cached version or not.

function *(next) {
  var options = {
    prerender: '....'
  };

  // an if would be nice here
  var cached = yield app.services.cache.fetch('prrnd_'+this.request.url).then(function(body) {
    return body;
  });

  if (cached) {
    this.response.body = cached;
  } else {
    yield prerender(options).call(this, next)

    if (this.response.is('html')) {
      // no need to wait for it to succeed or fail
      app.services.cache.set('prrnd_'+this.request.url, this.response.body)
    }
  }
};

mitom avatar Dec 14 '15 21:12 mitom