Skip to content

Commit

Permalink
Small worker fixes
Browse files Browse the repository at this point in the history
  • Loading branch information
lalalune committed Feb 8, 2024
1 parent 61f6660 commit 6c71222
Show file tree
Hide file tree
Showing 3 changed files with 110 additions and 17 deletions.
5 changes: 5 additions & 0 deletions packages/app/src/App.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@ import Error404 from "./pages/404/Error404";
import RoomLayout from "./pages/app/Room/index";
import Root from "./pages/app/root";
import UserPreferences from "./pages/app/UserPreferences/UserPreferences";
import TestPage from "./pages/app/TestPage";
import useGlobalStore from "./store/useGlobalStore";

const supabase = createClient(
Expand All @@ -39,6 +40,10 @@ const router = createBrowserRouter([
path: "/account",
element: <UserPreferences />,
},
{
path: "/test",
element: <TestPage />,
},
],
},
]);
Expand Down
83 changes: 83 additions & 0 deletions packages/app/src/pages/app/TestPage.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,83 @@
import { Avatar, Button, Divider, Flex, Grid, TextInput } from "@mantine/core";
import { useMediaQuery } from "@mantine/hooks";
import { closeAllModals, openModal } from "@mantine/modals";
import { showNotification } from "@mantine/notifications";
import { useSession, useSupabaseClient } from "@supabase/auth-helpers-react";
import React, { useState } from "react";
import { Save, User } from "react-feather";
import { useForm } from "react-hook-form";
import UploadProfileImage from "../../components/RegisterUser/helpers/UploadProfileImage.tsx/UploadProfileImage";
import { Database } from "../../../types/database.types";
import constants from "../../constants/constants";
import useGlobalStore from "../../store/useGlobalStore";

interface IFormValues {
name: string;
}

const TestPage = (): JSX.Element => {
const { user, setUser } = useGlobalStore();
const session = useSession();
const supabase = useSupabaseClient<Database>();


return (
<div>
<button onClick={async () =>
{
const response = await fetch(
`http://localhost:7998/api/ai/chat/completions`,
{
method: "POST",
headers: {
"Content-Type": "application/json",
Authorization: `Bearer ${session?.access_token}`,
},
body: JSON.stringify({
stop,
model: "gpt-3.5-turbo-0125",
frequency_penalty: 0,
presence_penalty: 0,
messages: [
{
role: "user",
content: "Please respond to this English text with a French translation: 'I love you'",
},
],
}),
},
);
try {
// check if error

if (response.status !== 200) {
// console.log(response.statusText);
// console.log(response.status);
console.log(await response.text());
throw new Error(
'OpenAI API Error: ' + response.status + ' ' + response.statusText
);
}

// if response has an error
if (!response.ok) {
throw new Error("Error in response: " + response.statusText);
}

const body = await response.json();

const content = body.choices?.[0]?.message?.content;
if (!content) {
throw new Error("No content in response", body);
}
console.log('content is', content)
window.alert(content);
} catch (error) {
throw new Error(error as any);
}
}}>Try request</button>
</div>
);
};

export default TestPage;
39 changes: 22 additions & 17 deletions packages/worker/src/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -76,27 +76,31 @@ class Server {
try {
req.pathname = pathname;

// const supabase = createClient(env.SUPABASE_URL, env.SUPABASE_SERVICE_API_KEY, {
// auth: {
// persistSession: false
// }
// });

// const token = req.headers.get('Authorization') &&
// req.headers.get('Authorization').replace('Bearer ', '');
const supabase = createClient(env.SUPABASE_URL, env.SUPABASE_SERVICE_API_KEY, {
auth: {
persistSession: false
}
});

const token = req.headers.get('Authorization') &&
req.headers.get('Authorization').replace('Bearer ', '');

// const out = await jwt.decode(token)
const out = token && await jwt.decode(token)


// const userId = out?.payload?.sub || out?.payload?.id || out?.id;
const userId = out?.payload?.sub || out?.payload?.id || out?.id;

// if(!userId) {
// return new Response('Unauthorized', { status: 401 });
// }

// console.log('userId', userId)
console.log('userId', userId)

return await fn({ req, env, match: matchUrl, host: matchHost, userId: null, supabase: null });
if(!userId) {
console.warn("Warning, userId is null, which means the token was not decoded properly. This will need to be fixed for security reasons.")
}

return await fn({ req, env, match: matchUrl, host: matchHost, userId, supabase });
} catch (err) {
console.log('erro', err)
return new Response(err, { status: 500 });
Expand All @@ -118,9 +122,9 @@ class Server {
const server = new Server();

const headers = {
// 'Access-Control-Allow-Origin': '*',
// 'Access-Control-Allow-Methods': '*',
// 'Access-Control-Allow-Headers': '*',
'Access-Control-Allow-Origin': '*',
'Access-Control-Allow-Methods': '*',
'Access-Control-Allow-Headers': '*',
}

server.registerHandler({
Expand All @@ -137,7 +141,6 @@ server.registerHandler({
server.registerHandler({
regex: /^\/api\/ai\/((?:completions|chat|files|embeddings|images|audio|assistants|threads)(?:\/.*)?)/,
async fn({ req, env, match }) {
console.log('calling openai', env.OPENAI_API_KEY)
const headers = {
'Authorization': `Bearer ${env.OPENAI_API_KEY}`,
};
Expand Down Expand Up @@ -242,7 +245,9 @@ export default {

function _setHeaders(res) {
for (const { key, value } of defaultHeaders) {
res.headers.append(key, value);
// if res.headers doesnt contain, add
if (!res.headers.has(key))
res.headers.append(key, value);
}
return res;
}

0 comments on commit 6c71222

Please sign in to comment.