Skip to content

Instantly share code, notes, and snippets.

@calvinfroedge
Created June 5, 2015 14:22
Show Gist options
  • Save calvinfroedge/080dfba68519bc926124 to your computer and use it in GitHub Desktop.
Save calvinfroedge/080dfba68519bc926124 to your computer and use it in GitHub Desktop.
Altered node-redis client, supports auto encryption, json, expiry, completely compatible with connect-redis
'use strict'
#deps
redis = require('redis')
cryptoService = require('../lib/crypto')
module.change_code = 1
'''
Possible options:
expiry: number of seconds till key is deleted from cache
secure: if set to true, data will be auto encrypted / decrypted via crypto service
json: if true, data will be automatically encoded / decoded as json when using GET or SET
'''
module.exports = (options={})->
#Create and configure the client
config = require('../config/redis')
redisClient = redis.createClient(config.port, config.hostname)
redisAuth = redisClient.auth(config.password)
#Log errors
redisClient.on 'error', (err) ->
console.log 'There was a redis error', err
return
#Since we are replace get and set
redisClient.my_command = (args, callback) ->
if !Array.isArray(args)
args = objToArray(arguments)
command = args[0]
args = args.splice(1)
if typeof callback == 'function'
@send_command command, args, callback
else
@send_command command, args
#Convenience method for flushdb
redisClient.empty = (callback) ->
if !callback
callback = (err, response) ->
if !err
console.log 'Successfully flushed all keys.'
if err
console.log 'Flushing all keys failed.'
return
redisClient.flushdb callback
return
#Altered API we want to expose
redisClient.get = (key, cb) ->
if !cb
cb = (err, data) ->
console.log 'err', err, 'data', data
return
redisClient.my_command ['get', key], (err, data)=>
if data and options.secure
data = cryptoService.decrypt(data)
if options.json and data and (data[0] == "{" or data[0] == "[")and (data[data.length - 1] == "}" or data[data.length -1 ] == "]")
data = JSON.parse(data)
cb err, data
return
return
redisClient.set = (key, data, cb) ->
if !cb
cb = (err) ->
console.log 'err', err
return
if typeof data == 'object' and options.json
data = JSON.stringify(data)
if options.secure
data = cryptoService.encrypt(data)
redisClient.my_command ['set', key, data], (err)=>
if not err and options.expiry
redisClient.expire key, options.expiry
cb err
return
redisClient
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment