Skip to content

Instantly share code, notes, and snippets.

@chrisvoo
Created March 19, 2019 14:40
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save chrisvoo/1314070744c8ccb1904c9c673d446bbc to your computer and use it in GitHub Desktop.
Save chrisvoo/1314070744c8ccb1904c9c673d446bbc to your computer and use it in GitHub Desktop.
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