Created
September 13, 2018 06:06
-
-
Save tcrowe/f1b76b0fad7f40f0f094ad7dacd38479 to your computer and use it in GitHub Desktop.
simple redis get set with json values
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
⚠️expires keys in 10min so it's only good for temp data | |
Install: | |
npm install redis lodash | |
Usage: | |
redisGet('my-key', (err, res) => { | |
if (err !== undefined && err !== null) { | |
return console.error('error getting redis key', key, err) | |
} | |
console.log('redisGet res', res) | |
}) | |
redisSet('my-key', {ok: true}, (err) => { | |
if (err !== undefined && err !== null) { | |
return console.error('error saving redis key', key, opts, err) | |
} | |
console.log('redisSet saved', key) | |
}) | |
*/ | |
let redis = require('redis') | |
let noop = require('lodash/noop') | |
let redisExpireSeconds = 600 // 10min | |
/** | |
* Get a key and parse as json | |
* @method redisGet | |
* @param {string} key | |
* @param {function} done | |
*/ | |
let redisGet = (key, done) => | |
redis.get(key, (err, res) => { | |
if (err !== null && err !== undefined) { | |
console.error('error reading redis', key, err) | |
return done(err) | |
} | |
if (res === null) { | |
return done(null, null) | |
} | |
done(null, JSON.parse(res)) | |
}) | |
/** | |
* Set a key and stringify the value into it | |
* ⚠️expires the key in 10min | |
* @method | |
* @param {string} key | |
* @param {object} opts | |
* @param {function} done | |
*/ | |
let redisSet = (key, opts, done = noop) => { | |
redis.set(key, JSON.stringify(opts), done) | |
redis.expire(key, redisExpireSeconds, noop) | |
} | |
module.exports = {redisGet, redisSet} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment