33import { headers } from "next/headers" ;
44import { getAuthServer } from "./auth" ;
55import { getDrizzle } from "./drizzle" ;
6- import { chat , message } from "@/schema/chat" ;
7- import { and , asc , eq } from "drizzle-orm" ;
6+ import { chat , message , section } from "@/schema/chat" ;
7+ import { and , asc , eq , exists } from "drizzle-orm" ;
88import { Auth } from "better-auth" ;
99import { revalidateTag , unstable_cacheLife } from "next/cache" ;
1010import { isCloudflare } from "./detectCloudflare" ;
@@ -54,6 +54,7 @@ export async function initContext(ctx?: Partial<Context>): Promise<Context> {
5454}
5555
5656export async function addChat (
57+ path : PagePath ,
5758 sectionId : SectionId ,
5859 messages : CreateChatMessage [ ] ,
5960 context ?: Partial < Context >
@@ -81,17 +82,21 @@ export async function addChat(
8182 )
8283 . returning ( ) ;
8384
84- revalidateTag ( cacheKeyForPage ( { } , userId ) ) ;
85+ revalidateTag ( cacheKeyForPage ( path , userId ) ) ;
8586 if ( isCloudflare ( ) ) {
8687 const cache = await caches . open ( "chatHistory" ) ;
8788 console . log (
88- `deleting cache for chatHistory/getChat for user ${ userId } and docs ${ lang } /${ page } `
89+ `deleting cache for chatHistory/getChat for user ${ userId } and docs ${ path . lang } /${ path . page } `
8990 ) ;
90- await cache . delete ( cacheKeyForPage ( { } , userId ) ) ;
91+ await cache . delete ( cacheKeyForPage ( path , userId ) ) ;
9192 }
9293
9394 return {
9495 ...newChat ,
96+ section : {
97+ sectionId,
98+ pagePath : `${ path . lang } /${ path . page } ` ,
99+ } ,
95100 messages : chatMessages ,
96101 } ;
97102}
@@ -108,8 +113,17 @@ export async function getChat(
108113 }
109114
110115 const chats = await drizzle . query . chat . findMany ( {
111- where : and ( eq ( chat . userId , userId ) , eq ( chat . docsId , docsId ) ) ,
116+ where : and (
117+ eq ( chat . userId , userId ) ,
118+ exists (
119+ drizzle
120+ . select ( )
121+ . from ( section )
122+ . where ( eq ( section . pagePath , `${ path . lang } /${ path . page } ` ) )
123+ )
124+ ) ,
112125 with : {
126+ section : true ,
113127 messages : {
114128 orderBy : [ asc ( message . createdAt ) ] ,
115129 } ,
0 commit comments