Eduards commited on
Commit
c575ee3
·
1 Parent(s): 6b13ecd

Use cookies instead of request body that is stale sometimes

Browse files
Files changed (1) hide show
  1. app/routes/api.chat.ts +27 -4
app/routes/api.chat.ts CHANGED
@@ -10,12 +10,35 @@ export async function action(args: ActionFunctionArgs) {
10
  return chatAction(args);
11
  }
12
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
13
  async function chatAction({ context, request }: ActionFunctionArgs) {
14
- const { messages, apiKeys } = await request.json<{
15
- messages: Messages,
16
- apiKeys: Record<string, string>
17
  }>();
18
 
 
 
 
 
 
19
  const stream = new SwitchableStream();
20
 
21
  try {
@@ -56,7 +79,7 @@ async function chatAction({ context, request }: ActionFunctionArgs) {
56
  });
57
  } catch (error) {
58
  console.log(error);
59
-
60
  if (error.message?.includes('API key')) {
61
  throw new Response('Invalid or missing API key', {
62
  status: 401,
 
10
  return chatAction(args);
11
  }
12
 
13
+ function parseCookies(cookieHeader) {
14
+ const cookies = {};
15
+
16
+ // Split the cookie string by semicolons and spaces
17
+ const items = cookieHeader.split(";").map(cookie => cookie.trim());
18
+
19
+ items.forEach(item => {
20
+ const [name, ...rest] = item.split("=");
21
+ if (name && rest) {
22
+ // Decode the name and value, and join value parts in case it contains '='
23
+ const decodedName = decodeURIComponent(name.trim());
24
+ const decodedValue = decodeURIComponent(rest.join("=").trim());
25
+ cookies[decodedName] = decodedValue;
26
+ }
27
+ });
28
+
29
+ return cookies;
30
+ }
31
+
32
  async function chatAction({ context, request }: ActionFunctionArgs) {
33
+ const { messages } = await request.json<{
34
+ messages: Messages
 
35
  }>();
36
 
37
+ const cookieHeader = request.headers.get("Cookie");
38
+
39
+ // Parse the cookie's value (returns an object or null if no cookie exists)
40
+ const apiKeys = JSON.parse(parseCookies(cookieHeader).apiKeys || "{}");
41
+
42
  const stream = new SwitchableStream();
43
 
44
  try {
 
79
  });
80
  } catch (error) {
81
  console.log(error);
82
+
83
  if (error.message?.includes('API key')) {
84
  throw new Response('Invalid or missing API key', {
85
  status: 401,