Question

I am adding caching (redis) into my project and would prefer to code it into the model logic rather than the controller. I would need to overwrite the model method and add the logic for the caching there.

I know I can override certain methods like find and findOne but I'm not sure what to return.

Example (pseudo)

findOne: function () {
  cache.get(key, function (err, data) {
    if (data === null) // No cache data
      // get the data and return it
    else
      // return the cache data
  });
}

The problem is that these model methods dont just return the data, they return an instance of the model itself (for chaining).

Not really sure how to return the data and how to get it if it isn't already set. Has anyone ever done anything like this?

Was it helpful?

Solution

Caching is something that we'd love for Waterline, but at the moment the only way to really get what you want is to create your own adapter. Overriding find and findOne is not really feasible at this point, as there's no good way to access the underlying "parent" methods in case your cache turned up empty and you wanted to proceed with the query.

In your case, forking one of the existing adapters (like sails-mysql) to add Redis caching would probably be more constructive than starting from scratch. If one could add the caching layer as a separate, installable module (i.e. a dependency) of the forked adapter, it would be easier to replicate the functionality across other adapters, and eventually roll into the adapter spec itself. If anyone felt like tackling this it would be a great contribution! You might also ask in the Sails IRC channel (irc://irc.freenode.net/sailsjs) to see if anyone's already working on something similar.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top