mirror of
https://github.com/mohamadihsan/topuponline.git
synced 2026-12-06 21:16:28 +00:00
46 lines
1.1 KiB
JavaScript
46 lines
1.1 KiB
JavaScript
// Perintah yang sudah terkirim baru dilepas oleh node-redis saat socket ditutup.
|
|
function createRedisOperations(client, { timeoutMs = 500, onTimeout = () => {} } = {}) {
|
|
let reconnecting = false;
|
|
|
|
function resetConnection() {
|
|
if (reconnecting) return;
|
|
reconnecting = true;
|
|
if (client.isOpen) {
|
|
client.disconnect().catch(() => {}).then(reconnect);
|
|
} else {
|
|
reconnect();
|
|
}
|
|
}
|
|
|
|
function reconnect() {
|
|
// Setelah socket lama dilepas, isReady milik klien menentukan kapan socket baru dapat dipakai.
|
|
reconnecting = false;
|
|
if (!client.isOpen) void client.connect().catch(() => {});
|
|
}
|
|
|
|
async function execute(command) {
|
|
if (!client.isReady || reconnecting) return null;
|
|
let timer;
|
|
try {
|
|
return await Promise.race([
|
|
command(client),
|
|
new Promise((resolve) => {
|
|
timer = setTimeout(() => {
|
|
onTimeout();
|
|
resetConnection();
|
|
resolve(null);
|
|
}, timeoutMs);
|
|
}),
|
|
]);
|
|
} catch {
|
|
return null;
|
|
} finally {
|
|
clearTimeout(timer);
|
|
}
|
|
}
|
|
|
|
return execute;
|
|
}
|
|
|
|
module.exports = createRedisOperations;
|