1
\$\begingroup\$

This code gets data from a MySQL database, such that if a key doesn't exist in a Redis database, then fetching of data needs to be done from the MySQL database and then stored in Redis cache. As such, the next time the key exists, querying to the MySQL database will be avoided.

Please see whether this can optimized or let me know if something needs to be changed.

somefile.js

var express = require('express');
var Promise = require("bluebird");
var getSqlConnection = require('../common/database');
var redisModules = require("../common/redismodule");

function getSettings(request, response) 
{
    if (redisModules.IsRedisConnectionOpened() == true) 
    {
        return GetData();
    }
    else 
    {
        response.status(500).send();
        return;
    }

    function GetData() 
    {
        redisModules.GetRedisValue("key")
        .then(function (result) 
        {
            if (!result) 
                return new SetData();      
            else 
                return result;
        })
        .catch(function (e) 
        {
            response.status(500).send();
        })
        .then(function (result) 
        {
            response.status(200).send({ value : result });
        });
    }

    function SetData()
    {
        return Promise.using(getSqlConnection(), function(connection) 
        {
            return connection.query('select url from blog')
            .then(function(results) 
            {
                var data = "";
                // some code
                return data;
            })
            .then(function (result) 
            {
                return new redisModules.SetRedisValue("key", result);
            });
        });
    }
}

database.js

File for handling database connections

var mysql = require('promise-mysql');

pool = mysql.createPool({
  host: '',
  user: '',
  password: '',
  database: '',
  connectionLimit: 4
});

function getSqlConnection() {
  return pool.getConnection().disposer(function(connection) {
    pool.releaseConnection(connection);
  });
}

module.exports = getSqlConnection;

redismodule.js

File for handling redis get, set concepts

var Promise = require('bluebird');
var constants = require('../common/contants');

var redisClient;        // Global (Avoids Duplicate Connections)

module.exports = 
{
    OpenRedisConnection : function()
    {
        if (redisClient == null) 
        {
            redisClient = require("redis").createClient(6379, 'localhost');
        }
    },
    IsRedisConnectionOpened : function()
    {
        if (redisClient && redisClient.connected == true) 
        {
            return true;
        }
        else 
        {
            if(redisClient)
                redisClient.end();  // End and open once more

            module.exports.OpenRedisConnection();
            return true;
        }
    },
    GetRedisValue: function (key) 
    {
        return new Promise(function (resolve, reject)
        {
            redisClient.get(key, function (error, result) 
            {
                if (error) 
                {
                    reject(error);
                }
                else 
                {
                    if (result == null)
                        resolve();    // Key not present so create
                    else
                        resolve(result);
                }
            });
        }); 
    },
    SetRedisValue: function (key, value) 
    {
        return new Promise(function (resolve, reject)
        {
            redisClient.set(key, value, 'EX', 1000, 
            function(err,reply) 
            {
                if (reply == 'OK')
                    resolve(value);         // Send the value
                else
                    reject(err);
            });
        }); 
    }
};

The execution starts when getSettings function is called.

I have just included all the code so that if it's correct it might be useful for others.

\$\endgroup\$
  • \$\begingroup\$ Does the code work correctly at what it's supposed to do? Please clarify. \$\endgroup\$ – Phrancis Jul 13 '17 at 21:11
  • \$\begingroup\$ it gives expected results. NO issues with it. But i wanted to check if i am implemented the promises concept correctly \$\endgroup\$ – Sharath Jul 14 '17 at 2:50
  • \$\begingroup\$ Thanks for clarifying. I edited your post to make this more clear. Hope you get great reviews! \$\endgroup\$ – Phrancis Jul 14 '17 at 3:25

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.