Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
simple redis get set with json values
/*
⚠️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
You can’t perform that action at this time.