Skip to content

Commit

Permalink
chore: use Redis
Browse files Browse the repository at this point in the history
  • Loading branch information
ijemmao authored Aug 14, 2024
1 parent 1f1dc83 commit 8c6d17b
Showing 1 changed file with 24 additions and 33 deletions.
57 changes: 24 additions & 33 deletions src/middleware/attachRedisClient.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { RedisClientType } from 'redis';
// import { REDIS_HOST, REDIS_PORT, REDIS_URL, REDIS_USERNAME, REDIS_PASSWORD } from '../config';
import { createClient, RedisClientType } from 'redis';
import { REDIS_HOST, REDIS_PORT, REDIS_URL, REDIS_USERNAME, REDIS_PASSWORD } from '../config';
import { MiddleWare } from '../types';

const afterResponse = (redisClient: RedisClientType) => {
Expand All @@ -13,47 +13,38 @@ const afterResponse = (redisClient: RedisClientType) => {
};

// Keep the same Redis Client connection open
export const redisClient = {
set: () => null,
get: () => null,
on: () => console.log('\nFake Redis client'),
connect: () => console.log('Connected to fake Redis client'),
isFake: true,
isReady: true,
};
// REDIS_HOST && REDIS_PORT && REDIS_USERNAME && REDIS_PASSWORD
// ? createClient({
// socket: {
// host: REDIS_HOST,
// port: REDIS_PORT,
// },
// username: REDIS_USERNAME,
// password: REDIS_PASSWORD,
// })
// : REDIS_URL && process.env.FIREBASE_FUNCTIONS
// ? createClient({
// url: 'redis://localhost:6379',
// })
// : {
// set: () => null,
// get: () => null,
// on: () => console.log('\nFake Redis client'),
// connect: () => console.log('Connected to fake Redis client'),
// isFake: true,
// isReady: true,
// };
export const redisClient =
REDIS_HOST && REDIS_PORT && REDIS_USERNAME && REDIS_PASSWORD
? createClient({
socket: {
host: REDIS_HOST,
port: REDIS_PORT,
},
username: REDIS_USERNAME,
password: REDIS_PASSWORD,
})
: REDIS_URL && process.env.FIREBASE_FUNCTIONS
? createClient({
url: 'redis://localhost:6379',
})
: {
set: () => null,
get: () => null,
on: () => console.log('\nFake Redis client'),
connect: () => console.log('Connected to fake Redis client'),
isFake: true,
isReady: true,
};

const attachRedisClient: MiddleWare = async (req, res, next) => {
if (!redisClient.isReady) {
redisClient.connect();
}
// @ts-expect-error redisClient
redisClient.on('error', (err: any) => console.log('Redis Client Error', err));

res.on('finish', afterResponse);
res.on('close', afterResponse);

// @ts-expect-error redisClient
req.redisClient = redisClient as RedisClientType;
return next();
};
Expand Down

0 comments on commit 8c6d17b

Please sign in to comment.