Skip to content

An AI-powered search engine with a generative UI

feat: add userId parameter to eliminate auth duplication

Yoshiki Miura51f1b3939996
diff --git a/lib/actions/chat.ts b/lib/actions/chat.ts
index 6abdf114..053a75e5 100644
--- a/lib/actions/chat.ts
+++ b/lib/actions/chat.ts
@@ -47,7 +47,9 @@ export async function getChat(
}
/**
- * Load a chat with messages (Vercel pattern)
+ * Load a chat with messages
+ * If requestingUserId is provided, it will be used for authorization
+ * Otherwise, no authorization check is performed (assumes already authorized)
*/
export async function loadChat(
chatId: string,
@@ -60,9 +62,14 @@ export async function loadChat(
/**
* Create a new chat
*/
-export async function createChat(id?: string, title?: string): Promise<Chat> {
- const userId = await getCurrentUserId()
- if (!userId) {
+export async function createChat(
+ id?: string,
+ title?: string,
+ userId?: string
+): Promise<Chat> {
+ // If userId is not provided, get it from auth
+ const uid = userId ?? (await getCurrentUserId())
+ if (!uid) {
throw new Error('User not authenticated')
}
@@ -73,7 +80,7 @@ export async function createChat(id?: string, title?: string): Promise<Chat> {
const chat = await dbActions.createChat({
id: chatId,
title: chatTitle.substring(0, 255),
- userId,
+ userId: uid,
visibility: 'private'
})
@@ -89,10 +96,12 @@ export async function createChat(id?: string, title?: string): Promise<Chat> {
*/
export async function createChatAndSaveMessage(
message: UIMessage,
- title?: string
+ title?: string,
+ userId?: string
): Promise<{ chat: Chat; message: Message }> {
- const userId = await getCurrentUserId()
- if (!userId) {
+ // If userId is not provided, get it from auth
+ const uid = userId ?? (await getCurrentUserId())
+ if (!uid) {
throw new Error('User not authenticated')
}
@@ -103,6 +112,40 @@ export async function createChatAndSaveMessage(
const chatTitle =
title || getTextFromParts(message.parts as any[]) || DEFAULT_CHAT_TITLE
+ // Create chat
+ const chat = await dbActions.createChat({
+ id: chatId,
+ title: chatTitle.substring(0, 255),
+ userId: uid,
+ visibility: 'private'
+ })
+
+ // Save message
+ const dbMessage = await dbActions.upsertMessage({
+ ...message,
+ id: messageId,
+ chatId
+ })
+
+ // Revalidate cache
+ revalidateTag(`chat-${chatId}`)
+
+ return { chat, message: dbMessage }
+}
+
+/**
+ * Create a new chat with the first message in a single transaction
+ * Optimized for new chat creation
+ */
+export async function createChatWithFirstMessage(
+ chatId: string,
+ message: UIMessage,
+ userId: string,
+ title?: string
+): Promise<{ chat: Chat; message: Message }> {
+ const messageId = message.id || generateId()
+ const chatTitle = title || DEFAULT_CHAT_TITLE
+
// Create chat
const chat = await dbActions.createChat({
id: chatId,
@@ -120,6 +163,7 @@ export async function createChatAndSaveMessage(
// Revalidate cache
revalidateTag(`chat-${chatId}`)
+ revalidateTag('chat')
return { chat, message: dbMessage }
}
@@ -136,19 +180,21 @@ export async function saveMessage(
}
/**
- * Upsert a message to a chat (Vercel pattern)
+ * Upsert a message to a chat
*/
export async function upsertMessage(
chatId: string,
- message: UIMessage
+ message: UIMessage,
+ userId?: string
): Promise<Message> {
- const userId = await getCurrentUserId()
- if (!userId) {
+ // If userId is not provided, get it from auth
+ const uid = userId ?? (await getCurrentUserId())
+ if (!uid) {
throw new Error('User not authenticated')
}
// Verify access
- const chat = await dbActions.getChat(chatId, userId)
+ const chat = await dbActions.getChat(chatId, uid)
if (!chat) {
throw new Error('Chat not found or unauthorized')
}
diff --git a/lib/streaming/helpers/handle-stream-finish.ts b/lib/streaming/helpers/handle-stream-finish.ts
index df97d1aa..5a5ca784 100644
--- a/lib/streaming/helpers/handle-stream-finish.ts
+++ b/lib/streaming/helpers/handle-stream-finish.ts
@@ -18,7 +18,7 @@ export async function handleStreamFinish(
context: StreamContext,
titlePromise?: Promise<string>
) {
- const { chatId, modelId, abortSignal, parentTraceId } = context
+ const { chatId, userId, modelId, abortSignal, parentTraceId } = context
// Attach metadata to the response message if we have a traceId
if (parentTraceId) {
@@ -77,11 +77,11 @@ export async function handleStreamFinish(
const chatTitle = titlePromise ? await titlePromise : undefined
// Save message with retry logic
- upsertMessage(chatId, responseMessage).catch(async error => {
+ upsertMessage(chatId, responseMessage, userId).catch(async error => {
console.error('Error saving message:', error)
try {
await retryDatabaseOperation(
- () => upsertMessage(chatId, responseMessage),
+ () => upsertMessage(chatId, responseMessage, userId),
'save message'
)
} catch (retryError) {
diff --git a/lib/streaming/helpers/prepare-messages.ts b/lib/streaming/helpers/prepare-messages.ts
index 486cbbc1..c513b203 100644
--- a/lib/streaming/helpers/prepare-messages.ts
+++ b/lib/streaming/helpers/prepare-messages.ts
@@ -57,7 +57,7 @@ export async function prepareMessages(
} else {
// User message edit
if (message && message.id === messageId) {
- await upsertMessage(chatId, message)
+ await upsertMessage(chatId, message, userId)
}
const messagesToDelete = currentChat.messages.slice(messageIndex + 1)
if (messagesToDelete.length > 0) {
@@ -80,10 +80,10 @@ export async function prepareMessages(
}
if (!initialChat) {
- await createChat(chatId, DEFAULT_CHAT_TITLE)
+ await createChat(chatId, DEFAULT_CHAT_TITLE, userId)
}
- await upsertMessage(chatId, messageWithId)
+ await upsertMessage(chatId, messageWithId, userId)
// If we have initialChat, append the new message instead of fetching all messages
if (initialChat && initialChat.messages) {