Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- const { promisify } = require('util');
- const redis = require('redis');
- const REDIS_URL = process.env.REDIS_URL || 'redis://localhost:6379';
- const CACHE_KEY_PREFIX = process.env.REDIS_GLOBAL_CACHE_KEY_PREFIX || '';
- const CACHE_TTL = process.env.REDIS_TTL || 60 * 5; // seconds
- const DEFAULT_VERSION = 1;
- const client = redis.createClient(REDIS_URL);
- const redisGet = promisify(client.get).bind(client);
- const redisSet = promisify(client.set).bind(client);
- const redisDelete = promisify(client.del).bind(client);
- const redisHget = promisify(client.hget).bind(client);
- const redisHset = promisify(client.hset).bind(client);
- const redisExists = promisify(client.exists).bind(client);
- function getCacheKey({ prefix, version, key }) {
- const cachePrefix = prefix || CACHE_KEY_PREFIX;
- const cacheVersion = version || DEFAULT_VERSION;
- return `${cachePrefix}-${cacheVersion}-${key}`;
- }
- function serialize(value) {
- if (typeof value === 'object') {
- return JSON.stringify(value);
- }
- return value;
- }
- function deSerialize(cachedValue) {
- try {
- return JSON.parse(cachedValue);
- } catch (error) {
- return cachedValue;
- }
- }
- async function get(key, options = {}) {
- const version = options.version || DEFAULT_VERSION;
- const cacheKey = getCacheKey({ key, version });
- return redisGet(cacheKey).then(result => deSerialize(result));
- }
- async function set(key, value, options = {}) {
- const ttl = options.ttl || CACHE_TTL;
- const version = options.version || DEFAULT_VERSION;
- const cacheKey = getCacheKey({ key, version });
- const serializedValue = serialize(value);
- if (!ttl) {
- return redisSet(cacheKey, serializedValue);
- }
- return redisSet(cacheKey, serializedValue, 'EX', ttl);
- }
- async function del(key, options = {}) {
- const version = options.version || DEFAULT_VERSION;
- const cacheKey = getCacheKey({ key, version });
- return redisDelete(cacheKey);
- }
- async function hget(key, field, options = {}) {
- const version = options.version || DEFAULT_VERSION;
- const cacheKey = getCacheKey({ key, version });
- return redisHget(cacheKey, field);
- }
- async function hset(key, field, value, options = {}) {
- const version = options.version || DEFAULT_VERSION;
- const cacheKey = getCacheKey({ key, version });
- return redisHset(cacheKey, field, value);
- }
- async function exists(key, options = {}) {
- const version = options.version || DEFAULT_VERSION;
- const cacheKey = getCacheKey({ key, version });
- return redisExists(cacheKey);
- }
- module.exports = {
- get,
- set,
- del,
- hget,
- hset,
- exists,
- };
Add Comment
Please, Sign In to add comment