File size: 1,140 Bytes
c3e8f3d
84c9f51
314f2dc
d0a1b70
c3e8f3d
314f2dc
973f0d8
c3e8f3d
d0a1b70
 
 
 
314f2dc
 
 
 
6b8f69a
 
26c4b30
314f2dc
 
 
 
 
 
 
 
 
 
 
26c4b30
314f2dc
 
 
 
 
 
 
26c4b30
314f2dc
26c4b30
314f2dc
973f0d8
314f2dc
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
import { auth } from '@/auth';
import { createKVChat } from '@/lib/kv/chat';
import { withLogging } from '@/lib/logger';
import { ChatEntity, MessageBase } from '@/lib/types';
import { nanoid } from '@/lib/utils';
import { Session } from 'next-auth';
import { revalidatePath } from 'next/cache';

/**
 * @param req
 * @returns
 */
export const POST = withLogging(
  async (
    session,
    json: {
      id?: string;
      url: string;
      initMessages?: MessageBase[];
    },
  ): Promise<Response> => {
    const user = session?.user?.email ?? 'anonymous';
    // if (!email) {
    //   return new Response('Unauthorized', {
    //     status: 401,
    //   });
    // }

    try {
      const { id, url, initMessages } = json;

      const payload: ChatEntity = {
        url,
        id: id ?? nanoid(),
        user,
        messages: initMessages ?? [],
        updatedAt: Date.now(),
      };

      await createKVChat(payload);

      revalidatePath('/chat', 'layout');

      return Response.json(payload);
    } catch (error) {
      return new Response((error as Error).message, {
        status: 400,
      });
    }
  },
);