62 lines
1.9 KiB
TypeScript
62 lines
1.9 KiB
TypeScript
import { getRedisClient } from '../realtime/redis/client';
|
|
import { supportRedisKeys } from '../realtime/redis/supportKeys';
|
|
|
|
export type SupportRealtimeEvent =
|
|
| {
|
|
type: 'message.new';
|
|
conversationId: string;
|
|
messageId: string;
|
|
message?: Record<string, unknown>;
|
|
}
|
|
| { type: 'message.read'; conversationId: string }
|
|
| { type: 'conversation.updated'; conversationId: string }
|
|
| { type: 'typing'; conversationId: string; party: 'user' | 'staff'; active: boolean };
|
|
|
|
const TYPING_TTL_SEC = 5;
|
|
|
|
export async function publishSupportEvent(
|
|
conversationId: string,
|
|
event: SupportRealtimeEvent
|
|
): Promise<void> {
|
|
const redis = getRedisClient();
|
|
if (!redis) return;
|
|
const payload = JSON.stringify({ ...event, ts: Date.now() });
|
|
await redis.publish(supportRedisKeys.pubsubConversation(conversationId), payload);
|
|
if (event.type !== 'typing') {
|
|
await redis.publish(supportRedisKeys.pubsubStaffInbox(), payload);
|
|
}
|
|
}
|
|
|
|
export async function setTypingIndicator(
|
|
conversationId: string,
|
|
party: 'user' | 'staff',
|
|
active: boolean
|
|
): Promise<void> {
|
|
const redis = getRedisClient();
|
|
if (!redis) return;
|
|
const key = supportRedisKeys.typing(conversationId, party);
|
|
if (active) {
|
|
await redis.set(key, '1', 'EX', TYPING_TTL_SEC);
|
|
} else {
|
|
await redis.del(key);
|
|
}
|
|
await publishSupportEvent(conversationId, {
|
|
type: 'typing',
|
|
conversationId,
|
|
party,
|
|
active,
|
|
});
|
|
}
|
|
|
|
export async function getTypingIndicators(
|
|
conversationId: string
|
|
): Promise<{ userTyping: boolean; staffTyping: boolean }> {
|
|
const redis = getRedisClient();
|
|
if (!redis) return { userTyping: false, staffTyping: false };
|
|
const [user, staff] = await Promise.all([
|
|
redis.get(supportRedisKeys.typing(conversationId, 'user')),
|
|
redis.get(supportRedisKeys.typing(conversationId, 'staff')),
|
|
]);
|
|
return { userTyping: user === '1', staffTyping: staff === '1' };
|
|
}
|