chatbot-template/app/actions.ts

65 lines
1.2 KiB
TypeScript
Raw Normal View History

2023-06-02 15:33:48 -04:00
'use server'
2023-05-19 12:33:56 -04:00
2023-06-02 15:33:48 -04:00
import { revalidatePath } from 'next/cache'
import { kv } from '@vercel/kv'
import { type Chat } from '@/lib/types'
2023-06-11 11:14:39 -04:00
export async function getChats(userId?: string | null) {
if (!userId) {
return []
}
try {
const pipeline = kv.pipeline()
const chats: string[] = await kv.zrange(`user:chat:${userId}`, 0, -1)
for (const chat of chats) {
pipeline.hgetall(chat)
}
const results = await pipeline.exec()
return results as Chat[]
} catch (error) {
return []
}
}
export async function getChat(id: string, userId: string) {
const chat = await kv.hgetall<Chat>(`chat:${id}`)
if (!chat) {
throw new Error('Not found')
}
if (userId && chat.userId !== userId) {
throw new Error('Unauthorized')
}
return chat
}
2023-05-19 12:33:56 -04:00
2023-06-02 14:28:05 -04:00
export async function removeChat({
id,
path,
2023-06-02 15:33:48 -04:00
userId
2023-06-02 14:28:05 -04:00
}: {
2023-06-02 15:33:48 -04:00
id: string
userId: string
path: string
2023-06-02 14:28:05 -04:00
}) {
2023-06-02 15:15:35 -04:00
// @todo next-auth@v5 doesn't work in server actions yet
2023-06-02 14:28:05 -04:00
// const session = await auth();
2023-06-02 15:33:48 -04:00
const uid = await kv.hget<string>(`chat:${id}`, 'userId')
2023-06-02 15:15:35 -04:00
if (uid !== userId) {
2023-06-02 15:33:48 -04:00
throw new Error('Unauthorized')
2023-06-02 15:15:35 -04:00
}
2023-06-02 15:33:48 -04:00
await kv.del(`chat:${id}`)
await kv.zrem(`user:chat:${userId}`, `chat:${id}`)
2023-05-19 12:33:56 -04:00
2023-06-02 15:33:48 -04:00
revalidatePath('/')
revalidatePath('/chat/[id]')
2023-05-19 12:33:56 -04:00
}