vision-agent / lib /kv /chat.ts
MingruiZhang's picture
Delete chat and clean up toggle into search params (#48)
d553ae5 unverified
raw
history blame
2.66 kB
'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
.filter(r => !!r)
.sort((r1, r2) => r2.updatedAt - r1.updatedAt);
} catch (error) {
console.error('getKVChats error:', 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(),
});
return revalidatePath('/chat', 'layout');
}
export async function removeKVChat(id: string) {
const { email } = await authEmail();
if (!email) {
return {
error: 'Unauthorized',
};
}
await Promise.all([
kv.zrem(`user:chat:${email}`, `chat:${id}`),
kv.del(`chat:${id}`),
]);
return revalidatePath('/chat', 'layout');
}