Skip to content

Instantly share code, notes, and snippets.

@chrisvoo chrisvoo/redis.js
Created Mar 19, 2019

Embed
What would you like to do?
Node.js and Redis: async GET/SET
const redis = require("redis")
const { promisify } = require("util")
const {
redis: { clientOptions, expire },
} = require("../config/get-config")
let client
/**
* Asynchronous version of `client.get`
* @param {string} key a Redis key
* @returns {Promise} the corresponding value of `key` or null if it doesn't exist
*/
function get(key) {
if (!client) {
client = redis.createClient(clientOptions)
}
const getAsync = promisify(client.get).bind(client)
return getAsync(key)
}
/**
* Sets a value inside Redis. Expiration is taken from the main configuration
* @param {string} key Redis key
* @param {string} val Redis value
* @returns {Promise} a reply string
* @see https://redis.io/commands/set
* @see https://redis.io/topics/protocol#simple-string-reply
*/
function set(key, val) {
if (!client) {
client = redis.createClient(clientOptions)
}
const setAsync = promisify(client.set).bind(client)
return setAsync(key, val, "EX", expire)
}
module.exports = {
get,
set,
}
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.