conversation.cache.ts48 lines, 1.3 KB
| 1 | import type { Conversation } from '@/types/conversation'; |
| 2 | |
| 3 | import { getRedisClient } from '@/clients/redis.client'; |
| 4 | |
| 5 | const CACHE_PREFIX = 'conversation:'; |
| 6 | const CACHE_TTL_SECONDS = 60; |
| 7 | |
| 8 | const serialize = (conversation: Conversation): string => { |
| 9 | return JSON.stringify({ |
| 10 | ...conversation, |
| 11 | createdAt: conversation.createdAt.toISOString(), |
| 12 | updatedAt: conversation.updatedAt.toISOString(), |
| 13 | }); |
| 14 | }; |
| 15 | |
| 16 | const deserialize = (raw: string): Conversation => { |
| 17 | const parsed = JSON.parse(raw) as Conversation & { |
| 18 | createdAt: string; |
| 19 | updatedAt: string; |
| 20 | }; |
| 21 | return { |
| 22 | ...parsed, |
| 23 | createdAt: new Date(parsed.createdAt), |
| 24 | updatedAt: new Date(parsed.updatedAt), |
| 25 | }; |
| 26 | }; |
| 27 | |
| 28 | export const conversationCache = { |
| 29 | async get(conversationId: string): Promise<Conversation | null> { |
| 30 | const redis = getRedisClient(); |
| 31 | const payload = await redis.get(`${CACHE_PREFIX}${conversationId}`); |
| 32 | return payload ? deserialize(payload) : null; |
| 33 | }, |
| 34 | |
| 35 | async set(conversation: Conversation): Promise<void> { |
| 36 | const redis = getRedisClient(); |
| 37 | await redis.setex( |
| 38 | `${CACHE_PREFIX}${conversation.id}`, |
| 39 | CACHE_TTL_SECONDS, |
| 40 | serialize(conversation), |
| 41 | ); |
| 42 | }, |
| 43 | |
| 44 | async delete(conversationId: string): Promise<void> { |
| 45 | const redis = getRedisClient(); |
| 46 | await redis.del(`${CACHE_PREFIX}${conversationId}`); |
| 47 | }, |
| 48 | }; |