vision-agent / lib /kv /chat.ts
MingruiZhang's picture
image rendering and vision agent endpoint boilerplate (#6)
a86b547 unverified
raw
history blame
1.62 kB
'use server';
import { revalidatePath } from 'next/cache';
import { kv } from '@vercel/kv';
import { auth } from '@/auth';
import { ChatEntity } from '@/lib/types';
import { redirect } from 'next/navigation';
async function authCheck() {
const session = await auth();
const email = session?.user?.email;
if (!email) {
redirect('/');
}
return { email, isAdmin: email.endsWith('landing.ai') };
}
export async function getKVChats() {
const { email } = await authCheck();
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();
return results as ChatEntity[];
} catch (error) {
return [];
}
}
export async function getKVChat(id: string) {
const { email, isAdmin } = await authCheck();
const chat = await kv.hgetall<ChatEntity>(`chat:${id}`);
if (chat?.user !== email || !isAdmin) {
redirect('/');
}
return chat;
}
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('/');
return revalidatePath(path);
}