Spaces:
Sleeping
Sleeping
'use server'; | |
import { revalidatePath } from 'next/cache'; | |
import { kv } from '@vercel/kv'; | |
import { auth, authEmail } from '@/auth'; | |
import { ChatEntity, MessageBase } from '@/lib/types'; | |
import { notFound, redirect } from 'next/navigation'; | |
import { nanoid } from '../utils'; | |
export async function getKVChats() { | |
const { email } = await authEmail(); | |
try { | |
const pipeline = kv.pipeline(); | |
const chats: string[] = await kv.zrange(`user:chat:${email}`, 0, -1, { | |
rev: true, | |
}); | |
for (const chat of chats) { | |
pipeline.hgetall(chat); | |
} | |
const results = (await pipeline.exec()) as ChatEntity[]; | |
return results.sort((r1, r2) => r2.updatedAt - r1.updatedAt); | |
} catch (error) { | |
return []; | |
} | |
} | |
export async function adminGetAllKVChats() { | |
const { isAdmin } = await authEmail(); | |
if (!isAdmin) { | |
notFound(); | |
} | |
try { | |
const pipeline = kv.pipeline(); | |
const chats: string[] = await kv.zrange(`user:chat:all`, 0, -1, { | |
rev: true, | |
}); | |
for (const chat of chats) { | |
pipeline.hgetall(chat); | |
} | |
const results = (await pipeline.exec()) as ChatEntity[]; | |
return results.sort((r1, r2) => r2.updatedAt - r1.updatedAt); | |
} catch (error) { | |
return []; | |
} | |
} | |
export async function getKVChat(id: string) { | |
// const { email, isAdmin } = await authEmail(); | |
const chat = await kv.hgetall<ChatEntity>(`chat:${id}`); | |
if (!chat) { | |
redirect('/'); | |
} | |
return chat; | |
} | |
export async function createKVChat(chat: ChatEntity) { | |
// const { email, isAdmin } = await authEmail(); | |
const { email } = await authEmail(); | |
await kv.hmset(`chat:${chat.id}`, chat); | |
if (email) { | |
await kv.zadd(`user:chat:${email}`, { | |
score: Date.now(), | |
member: `chat:${chat.id}`, | |
}); | |
} | |
await kv.zadd('user:chat:all', { | |
score: Date.now(), | |
member: `chat:${chat.id}`, | |
}); | |
revalidatePath('/chat', 'layout'); | |
} | |
export async function saveKVChatMessage(id: string, message: MessageBase) { | |
const chat = await kv.hgetall<ChatEntity>(`chat:${id}`); | |
if (!chat) { | |
notFound(); | |
} | |
const { messages } = chat; | |
await kv.hmset(`chat:${id}`, { | |
...chat, | |
messages: [...messages, message], | |
updatedAt: Date.now(), | |
}); | |
revalidatePath('/chat', 'layout'); | |
} | |
export async function removeKVChat({ id, path }: { id: string; path: string }) { | |
const session = await auth(); | |
if (!session) { | |
return { | |
error: 'Unauthorized', | |
}; | |
} | |
//Convert uid to string for consistent comparison with session.user.id | |
const uid = String(await kv.hget(`chat:${id}`, 'userId')); | |
if (uid !== session?.user?.id) { | |
return { | |
error: 'Unauthorized', | |
}; | |
} | |
await kv.del(`chat:${id}`); | |
await kv.zrem(`user:chat:${session.user.id}`, `chat:${id}`); | |
revalidatePath('/chat/layout', 'layout'); | |
return revalidatePath(path); | |
} | |