Redis Client (Node.js)
JS
S
JavaScriptNode.js client for Redis. Enables efficient data storage, retrieval, and caching in Node applications using Redis as a key-value database or message broker.
1import redis from 'redis';
2import moment from 'moment';
3import { promisify } from 'util';
4
5import logService from '../services/log';
6class MemoryCache {
7 // private fallbackMemoryClient: Map<string, any> = new Map();
8 public redisClient: redis.RedisClient;
9 public regisGetAsync: Promise<any>;
10
11 constructor() {
12 logService.log('info', 'Memory cache singleton running');
13 const options = {
14 host: process.env.REDIS_URI,
15 port: 6379,
16 max_attempts: 1,
17 };
18 this.redisClient = redis.createClient(options);
19 this.regisGetAsync = promisify(this.redisClient.get).bind(this.redisClient);
20 this.redisClient.on('error', (err) => {
21 logService.log('error', 'Redis client failed', err);
22 });
23 this.redisClient.on('connect', () => {
24 logService.log('info', 'Redis client created');
25 });
26 }
27 setCache(key: string, data: any, ttl?: number, checkSum?: string) {
28 if (this.redisClient.connected) {
29 if (key && data) {
30 const stringifiedData = JSON.stringify(data);
31 this.redisClient.del(key);
32 this.redisClient.set(key, stringifiedData);
33 this.redisClient.expire(key, ttl || 172800); // 48h
34 logService.log('info', 'Data store in cache', { key, ttl });
35 } else {
36 logService.log('error', 'Failed to store in cache - Invalid payload');
37 }
38 }
39 }
40
41 getCache(key: string, checkSum?: string) {
42 return new Promise((resolve, reject) => {
43 if (!this.redisClient.connected) {
44 return reject('Cache disconnected');
45 }
46 this.redisClient.get(key, (err, res) => {
47 if (err) {
48 logService.log('warning', 'Failed to retrieve', err);
49 return reject('No data found');
50 }
51 if (!res) {
52 logService.log('warning', 'Failed to retrieve / Cache miss');
53 return reject('No data found');
54 }
55 if (res) {
56 logService.log('info', 'Attempting to parse result');
57 try {
58 const parsedData = JSON.parse(res);
59 logService.log('info', 'Completed parsing');
60 if (!parsedData) {
61 logService.log('error', 'Failed to parse result');
62 reject('No data found');
63 }
64 resolve(parsedData);
65 } catch (err) {
66 logService.log('error', 'Failed to parse result');
67 reject('No data found');
68 }
69 }
70 });
71 });
72 }
73 clearCache(key: string) {
74 logService.log('info', `Cache invalidated for ${key}`);
75 return this.redisClient.del(key); // don't wait
76 }
77}
78
79const mc = new MemoryCache();
80export { mc as MemoryCache };
81
82
83
84// Cache Invalidator
85import { UserFacingError } from '../classes/errors';
86import { MemoryCache } from '../services/memory-cache';
87
88export function InvalidateCache(cacheKeys: string[]) {
89 return function validator(target: any, key: any, descriptor: any) {
90 const fn = descriptor.value;
91 descriptor.value = function (...args: any[]) {
92 cacheKeys.forEach((cacheKey) => {
93 MemoryCache.clearCache(cacheKey);
94 });
95 return fn.apply(this, args);
96 };
97 };
98}
99Created on 10/12/2020