81 lines
2.8 KiB
JavaScript
81 lines
2.8 KiB
JavaScript
"use strict";
|
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
exports.serializeRealtimeEvent = serializeRealtimeEvent;
|
|
exports.parseRealtimeEvent = parseRealtimeEvent;
|
|
exports.publishRoundEvent = publishRoundEvent;
|
|
exports.publishUserEvent = publishUserEvent;
|
|
exports.subscribeRoundEvents = subscribeRoundEvents;
|
|
exports.subscribeUserEvents = subscribeUserEvents;
|
|
const client_1 = require("./client");
|
|
const keys_1 = require("./keys");
|
|
function serializeRealtimeEvent(event) {
|
|
return JSON.stringify({ ...event, ts: event.ts ?? Date.now() });
|
|
}
|
|
function parseRealtimeEvent(raw) {
|
|
try {
|
|
const parsed = JSON.parse(raw);
|
|
if (!parsed?.type || typeof parsed.type !== 'string')
|
|
return null;
|
|
const payload = parsed.payload && typeof parsed.payload === 'object' && !Array.isArray(parsed.payload)
|
|
? parsed.payload
|
|
: {};
|
|
return {
|
|
type: parsed.type,
|
|
intervalMinutes: parsed.intervalMinutes,
|
|
payload,
|
|
version: parsed.version,
|
|
ts: typeof parsed.ts === 'number' ? parsed.ts : Date.now(),
|
|
};
|
|
}
|
|
catch {
|
|
return null;
|
|
}
|
|
}
|
|
async function publishRoundEvent(intervalMinutes, event) {
|
|
const redis = (0, client_1.getRedisClient)();
|
|
if (!redis)
|
|
return;
|
|
await redis.publish(keys_1.redisKeys.pubsubRound(intervalMinutes), serializeRealtimeEvent(event));
|
|
}
|
|
async function publishUserEvent(userId, event) {
|
|
const redis = (0, client_1.getRedisClient)();
|
|
if (!redis)
|
|
return;
|
|
await redis.publish(keys_1.redisKeys.pubsubUser(userId), serializeRealtimeEvent(event));
|
|
}
|
|
/** Subscribe to round channel; returns unsubscribe function. */
|
|
async function subscribeRoundEvents(intervalMinutes, handler) {
|
|
const sub = (0, client_1.getRedisSubscriber)();
|
|
if (!sub)
|
|
return async () => undefined;
|
|
const channel = keys_1.redisKeys.pubsubRound(intervalMinutes);
|
|
const onMessage = (_ch, message) => {
|
|
const event = parseRealtimeEvent(message);
|
|
if (event)
|
|
handler(event);
|
|
};
|
|
sub.on('message', onMessage);
|
|
await sub.subscribe(channel);
|
|
return async () => {
|
|
sub.off('message', onMessage);
|
|
await sub.unsubscribe(channel);
|
|
};
|
|
}
|
|
async function subscribeUserEvents(userId, handler) {
|
|
const sub = (0, client_1.getRedisSubscriber)();
|
|
if (!sub)
|
|
return async () => undefined;
|
|
const channel = keys_1.redisKeys.pubsubUser(userId);
|
|
const onMessage = (_ch, message) => {
|
|
const event = parseRealtimeEvent(message);
|
|
if (event)
|
|
handler(event);
|
|
};
|
|
sub.on('message', onMessage);
|
|
await sub.subscribe(channel);
|
|
return async () => {
|
|
sub.off('message', onMessage);
|
|
await sub.unsubscribe(channel);
|
|
};
|
|
}
|
|
//# sourceMappingURL=pubsub.js.map
|