fix: actions

This commit is contained in:
shadcn 2023-06-16 21:52:01 +04:00
parent 071778533c
commit cb941daca9
17 changed files with 277 additions and 65 deletions

View file

@ -1,9 +1,10 @@
'use server'
import { revalidatePath } from 'next/cache'
import { redirect } from 'next/navigation'
import { kv } from '@vercel/kv'
import { auth } from '@/auth'
import { auth } from '@/auth'
import { type Chat } from '@/lib/types'
export async function getChats(userId?: string | null) {
@ -32,12 +33,8 @@ export async function getChats(userId?: string | null) {
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')
if (!chat || (userId && chat.userId !== userId)) {
return null
}
return chat
@ -47,41 +44,36 @@ export async function removeChat({ id, path }: { id: string; path: string }) {
const session = await auth()
if (!session) {
throw new Error('Unauthorized')
return {
error: 'Unauthorized'
}
}
const uid = await kv.hget<string>(`chat:${id}`, 'userId')
if (uid !== session?.user?.id) {
throw new Error('Unauthorized')
return {
error: 'Unauthorized'
}
}
await kv.del(`chat:${id}`)
await kv.zrem(`user:chat:${session.user.id}`, `chat:${id}`)
revalidatePath('/')
revalidatePath(path)
return revalidatePath(path)
}
export async function clearChats() {
const session = await auth()
if (!session) {
throw new Error('Unauthorized')
}
if (!session.user?.id) {
throw new Error('Unauthorized')
}
const chats: string[] = await kv.zrange(
`user:chat:${session.user.id}`,
0,
-1,
{
rev: true
if (!session?.user?.id) {
return {
error: 'Unauthorized'
}
)
}
const chats: string[] = await kv.zrange(`user:chat:${session.user.id}`, 0, -1)
const pipeline = kv.pipeline()
@ -93,6 +85,7 @@ export async function clearChats() {
await pipeline.exec()
revalidatePath('/')
return redirect('/')
}
export async function getSharedChat(id: string) {
@ -108,16 +101,10 @@ export async function getSharedChat(id: string) {
export async function shareChat(chat: Chat) {
const session = await auth()
if (!session) {
throw new Error('Unauthorized')
}
if (!session.user?.id) {
throw new Error('Unauthorized')
}
if (chat.userId !== session.user?.id) {
throw new Error('Unauthorized')
if (!session?.user?.id || session.user.id !== chat.userId) {
return {
error: 'Unauthorized'
}
}
const payload = {