Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sails JS with Redis for caching

As I said in my previous questions, I am trying to learn how to use sails.js, what I'm trying to do now is to cache the response of an api to redis. I have searched on how to do this, but I can't make it to work. Without caching, I call the api through ajax.

Any thoughts on how I will be able to do it using my controller? How can I call the api using the controller in sails.js and cache the response using redis?

like image 785
bless1204 Avatar asked May 28 '15 05:05

bless1204


People also ask

Is Redis good for caching?

Caching. Redis is a great choice for implementing a highly available in-memory cache to decrease data access latency, increase throughput, and ease the load off your relational or NoSQL database and application.

How is Redis used for caching?

How Redis cache works is by assigning the original database query as the key and then resulting data as the value. Now, the Redis system can access the resulting database call by using the key which it has stored in its built-in temporary memory.

How does Redis store data in node JS?

Create new session. js file in the root directory with the following content: const express = require('express'); const session = require('express-session'); const redis = require('redis'); const client = redis. createClient(); const redisStore = require('connect-redis')(session); const app = express(); app.


1 Answers

You can use https://github.com/mranney/node_redis

Steps:

Add to package.json

"redis": "^0.12.1"

Run

npm install

Create a service module /api/services/CachedLookup.js

var redis = require("redis"),
  client = redis.createClient();

module.exports = {

  rcGet: function (key, cb) {
    client.get(key, function (err, value) {
      return cb(value);
    });
  },

  fetchApi1: function (cb) {
    var key = 'KEY'
    CachedLookup.rcGet(key, function (cachedValue) {
      if (cachedValue)
        return cb(cachedValue)
     else {//fetch the api and cache the result
        var request = require('request');
        request.post({
          url: URL,
          form: {}
        }, function (error, response, body) {
            if(error) {
               //handle error
            }
            else {
            client.set(key, response);
            return cb(response)
            }
        });
      }
    });
  }
}

Inside the controller

CachedLookup.fetchApi1(function (apiResponse) {
      res.view({
        apiResponse: apiResponse
      });
    });
like image 199
Muntasim Avatar answered Nov 08 '22 02:11

Muntasim