mirror of
https://github.com/mohamadihsan/topuponline.git
synced 2026-12-05 11:06:28 +00:00
46 lines
1.4 KiB
JavaScript
46 lines
1.4 KiB
JavaScript
require('dotenv').config();
|
|
const redis = require('redis');
|
|
const createRedisOperations = require('../helpers/redis-operations');
|
|
const { logger } = require('../helpers/winston.logger');
|
|
|
|
const redisClient = redis.createClient({
|
|
url: process.env.REDIS_URL || 'redis://127.0.0.1:6379',
|
|
disableOfflineQueue: true,
|
|
commandsQueueMaxLength: 256,
|
|
});
|
|
|
|
redisClient.on('error', () => {});
|
|
redisClient.on('ready', () => logger.info('Redis connection ready'));
|
|
void redisClient.connect().catch(() => logger.error('Redis connection failed'));
|
|
|
|
const execute = createRedisOperations(redisClient, {
|
|
onTimeout: () => logger.warn('Redis command deadline exceeded'),
|
|
});
|
|
|
|
async function redisMiddleware(req, res, next) {
|
|
const value = await execute((client) => client.get('cardproduct'));
|
|
if (value) {
|
|
try {
|
|
res.status(200).json({ code: 200, message: 'Success get from redis', data: JSON.parse(value) });
|
|
return;
|
|
} catch {
|
|
// Payload cache yang rusak dapat dibaca ulang dari sumbernya.
|
|
}
|
|
}
|
|
res.once('finish', () => {
|
|
if (res.body !== undefined) void execute((client) => client.set('cardproduct', JSON.stringify(res.body), { EX: 10 }));
|
|
});
|
|
next();
|
|
}
|
|
|
|
async function closeRedis() {
|
|
if (!redisClient.isOpen) return;
|
|
try {
|
|
await redisClient.quit();
|
|
} catch {
|
|
if (redisClient.isOpen) await redisClient.disconnect().catch(() => {});
|
|
}
|
|
}
|
|
|
|
module.exports = { redisMiddleware, closeRedis };
|