@@ -19,7 +19,7 @@ const CACHE_KEY_BASE = "https://my-code.utcode.net/chatHistory";
1919interface Context {
2020 drizzle : Awaited < ReturnType < typeof getDrizzle > > ;
2121 auth : Auth ;
22- userId : string ;
22+ userId ? : string ;
2323}
2424/**
2525 * drizzleが初期化されてなければ初期化し、
@@ -40,10 +40,9 @@ async function initAll(ctx?: Partial<Context>): Promise<Context> {
4040 const session = await ctx . auth . api . getSession ( {
4141 headers : await headers ( ) ,
4242 } ) ;
43- if ( ! session ) {
44- throw new Error ( "Not authenticated" ) ;
43+ if ( session ) {
44+ ctx . userId = session . user . id ;
4545 }
46- ctx . userId = session . user . id ;
4746 }
4847 return ctx as Context ;
4948}
@@ -64,7 +63,9 @@ export async function addChat(
6463 context ?: Partial < Context >
6564) {
6665 const { drizzle, userId } = await initAll ( context ) ;
67-
66+ if ( ! userId ) {
67+ throw new Error ( "Not authenticated" ) ;
68+ }
6869 const [ newChat ] = await drizzle
6970 . insert ( chat )
7071 . values ( {
@@ -106,6 +107,9 @@ export async function getChat(
106107 context ?: Partial < Context >
107108) : Promise < ChatWithMessages [ ] > {
108109 const { drizzle, userId } = await initAll ( context ) ;
110+ if ( ! userId ) {
111+ return [ ] ;
112+ }
109113
110114 const chats = await drizzle . query . chat . findMany ( {
111115 where : and ( eq ( chat . userId , userId ) , eq ( chat . docsId , docsId ) ) ,
@@ -131,6 +135,9 @@ export async function getChatFromCache(
131135 context ?: Partial < Context >
132136) {
133137 const { drizzle, auth, userId } = await initAll ( context ) ;
138+ if ( ! userId ) {
139+ return [ ] ;
140+ }
134141
135142 const cache = await getCache ( ) ;
136143 const cachedResponse = await cache . match (
0 commit comments