feat: refactor chat sharing implementation

This commit is contained in:
shadcn 2023-06-16 16:18:52 +04:00
parent 8cc3fea048
commit 137bdadaf9
12 changed files with 262 additions and 124 deletions

View file

@ -2,10 +2,9 @@
import { revalidatePath } from 'next/cache'
import { kv } from '@vercel/kv'
import { currentUser } from '@clerk/nextjs'
import { type Chat } from '@/lib/types'
import { currentUser } from '@clerk/nextjs'
import { nanoid } from '@/lib/utils'
export async function getChats(userId?: string | null) {
if (!userId) {
@ -52,9 +51,11 @@ export async function removeChat({ id, path }: { id: string; path: string }) {
}
const uid = await kv.hget<string>(`chat:${id}`, 'userId')
if (uid !== user.id) {
throw new Error('Unauthorized')
}
await kv.del(`chat:${id}`)
await kv.zrem(`user:chat:${user.id}`, `chat:${id}`)
@ -85,6 +86,16 @@ export async function clearChats() {
revalidatePath('/')
}
export async function getSharedChat(id: string) {
const chat = await kv.hgetall<Chat>(`chat:${id}`)
if (!chat || !chat.sharePath) {
return null
}
return chat
}
export async function shareChat(chat: Chat) {
const user = await currentUser()
@ -92,23 +103,12 @@ export async function shareChat(chat: Chat) {
throw new Error('Unauthorized')
}
const id = nanoid()
const createdAt = Date.now()
const payload = {
id,
title: chat.title,
userId: user.id,
createdAt,
path: `/share/${id}`,
chat
...chat,
sharePath: `/share/${chat.id}`
}
await kv.hmset(`share:${id}`, payload)
await kv.zadd(`user:share:${user.id}`, {
score: createdAt,
member: `share:${id}`
})
await kv.hmset(`chat:${chat.id}`, payload)
return payload
}