aboutsummaryrefslogtreecommitdiff
path: root/apps/web/src/app/api
diff options
context:
space:
mode:
Diffstat (limited to 'apps/web/src/app/api')
-rw-r--r--apps/web/src/app/api/ask/route.ts80
-rw-r--r--apps/web/src/app/api/chat/route.ts139
-rw-r--r--apps/web/src/app/api/me/route.ts45
-rw-r--r--apps/web/src/app/api/query/route.ts88
-rw-r--r--apps/web/src/app/api/store/route.ts219
5 files changed, 350 insertions, 221 deletions
diff --git a/apps/web/src/app/api/ask/route.ts b/apps/web/src/app/api/ask/route.ts
index cad7a671..89123ac9 100644
--- a/apps/web/src/app/api/ask/route.ts
+++ b/apps/web/src/app/api/ask/route.ts
@@ -7,42 +7,62 @@ import { env } from "@/env";
export const runtime = "edge";
export async function POST(req: NextRequest) {
- const token = req.cookies.get("next-auth.session-token")?.value ?? req.cookies.get("__Secure-authjs.session-token")?.value ?? req.cookies.get("authjs.session-token")?.value ?? req.headers.get("Authorization")?.replace("Bearer ", "");
+ const token =
+ req.cookies.get("next-auth.session-token")?.value ??
+ req.cookies.get("__Secure-authjs.session-token")?.value ??
+ req.cookies.get("authjs.session-token")?.value ??
+ req.headers.get("Authorization")?.replace("Bearer ", "");
- const sessionData = await db.select().from(sessions).where(eq(sessions.sessionToken, token!))
+ const sessionData = await db
+ .select()
+ .from(sessions)
+ .where(eq(sessions.sessionToken, token!));
- if (!sessionData || sessionData.length === 0) {
- return new Response(JSON.stringify({ message: "Invalid Key, session not found." }), { status: 404 });
- }
+ if (!sessionData || sessionData.length === 0) {
+ return new Response(
+ JSON.stringify({ message: "Invalid Key, session not found." }),
+ { status: 404 },
+ );
+ }
- const user = await db.select().from(users).where(eq(users.id, sessionData[0].userId)).limit(1)
+ const user = await db
+ .select()
+ .from(users)
+ .where(eq(users.id, sessionData[0].userId))
+ .limit(1);
- if (!user || user.length === 0) {
- return NextResponse.json({ message: "Invalid Key, session not found." }, { status: 404 });
- }
+ if (!user || user.length === 0) {
+ return NextResponse.json(
+ { message: "Invalid Key, session not found." },
+ { status: 404 },
+ );
+ }
- const body = await req.json() as {
- query: string;
- }
+ const body = (await req.json()) as {
+ query: string;
+ };
- const resp = await fetch(`https://cf-ai-backend.dhravya.workers.dev/ask`, {
- headers: {
- "X-Custom-Auth-Key": env.BACKEND_SECURITY_KEY,
- },
- method: "POST",
- body: JSON.stringify({
- query: body.query,
- }),
- })
+ const resp = await fetch(`https://cf-ai-backend.dhravya.workers.dev/ask`, {
+ headers: {
+ "X-Custom-Auth-Key": env.BACKEND_SECURITY_KEY,
+ },
+ method: "POST",
+ body: JSON.stringify({
+ query: body.query,
+ }),
+ });
- if (resp.status !== 200 || !resp.ok) {
- const errorData = await resp.json();
- return new Response(JSON.stringify({ message: "Error in CF function", error: errorData }), { status: resp.status });
- }
+ if (resp.status !== 200 || !resp.ok) {
+ const errorData = await resp.json();
+ return new Response(
+ JSON.stringify({ message: "Error in CF function", error: errorData }),
+ { status: resp.status },
+ );
+ }
- // Stream the response back to the client
- const { readable, writable } = new TransformStream();
- resp && resp.body!.pipeTo(writable);
+ // Stream the response back to the client
+ const { readable, writable } = new TransformStream();
+ resp && resp.body!.pipeTo(writable);
- return new Response(readable, { status: 200 });
-} \ No newline at end of file
+ return new Response(readable, { status: 200 });
+}
diff --git a/apps/web/src/app/api/chat/route.ts b/apps/web/src/app/api/chat/route.ts
index aec5b0ea..bc7a4ee4 100644
--- a/apps/web/src/app/api/chat/route.ts
+++ b/apps/web/src/app/api/chat/route.ts
@@ -8,60 +8,85 @@ import { ChatHistory } from "../../../../types/memory";
export const runtime = "edge";
export async function POST(req: NextRequest) {
- const token = req.cookies.get("next-auth.session-token")?.value ?? req.cookies.get("__Secure-authjs.session-token")?.value ?? req.cookies.get("authjs.session-token")?.value ?? req.headers.get("Authorization")?.replace("Bearer ", "");
-
- const sessionData = await db.select().from(sessions).where(eq(sessions.sessionToken, token!))
-
- if (!sessionData || sessionData.length === 0) {
- return new Response(JSON.stringify({ message: "Invalid Key, session not found." }), { status: 404 });
- }
-
- const user = await db.select().from(users).where(eq(users.id, sessionData[0].userId)).limit(1)
-
- if (!user || user.length === 0) {
- return NextResponse.json({ message: "Invalid Key, session not found." }, { status: 404 });
- }
-
- const session = { session: sessionData[0], user: user[0] }
-
- const query = new URL(req.url).searchParams.get("q");
- const spaces = new URL(req.url).searchParams.get("spaces");
-
- const sourcesOnly = new URL(req.url).searchParams.get("sourcesOnly") ?? "false";
-
- const chatHistory = await req.json() as {
- chatHistory: ChatHistory[]
- };
-
- console.log("CHathistory", chatHistory)
-
- if (!query) {
- return new Response(JSON.stringify({ message: "Invalid query" }), { status: 400 });
- }
-
-
- const resp = await fetch(`https://cf-ai-backend.dhravya.workers.dev/chat?q=${query}&user=${session.user.email ?? session.user.name}&sourcesOnly=${sourcesOnly}&spaces=${spaces}`, {
- headers: {
- "X-Custom-Auth-Key": env.BACKEND_SECURITY_KEY,
- },
- method: "POST",
- body: JSON.stringify({
- chatHistory: chatHistory.chatHistory ?? []
- })
- })
-
- console.log(resp.status)
- console.log(resp.statusText)
-
- if (resp.status !== 200 || !resp.ok) {
- const errorData = await resp.json();
- console.log(errorData)
- return new Response(JSON.stringify({ message: "Error in CF function", error: errorData }), { status: resp.status });
- }
-
- // Stream the response back to the client
- const { readable, writable } = new TransformStream();
- resp && resp.body!.pipeTo(writable);
-
- return new Response(readable, { status: 200 });
-} \ No newline at end of file
+ const token =
+ req.cookies.get("next-auth.session-token")?.value ??
+ req.cookies.get("__Secure-authjs.session-token")?.value ??
+ req.cookies.get("authjs.session-token")?.value ??
+ req.headers.get("Authorization")?.replace("Bearer ", "");
+
+ const sessionData = await db
+ .select()
+ .from(sessions)
+ .where(eq(sessions.sessionToken, token!));
+
+ if (!sessionData || sessionData.length === 0) {
+ return new Response(
+ JSON.stringify({ message: "Invalid Key, session not found." }),
+ { status: 404 },
+ );
+ }
+
+ const user = await db
+ .select()
+ .from(users)
+ .where(eq(users.id, sessionData[0].userId))
+ .limit(1);
+
+ if (!user || user.length === 0) {
+ return NextResponse.json(
+ { message: "Invalid Key, session not found." },
+ { status: 404 },
+ );
+ }
+
+ const session = { session: sessionData[0], user: user[0] };
+
+ const query = new URL(req.url).searchParams.get("q");
+ const spaces = new URL(req.url).searchParams.get("spaces");
+
+ const sourcesOnly =
+ new URL(req.url).searchParams.get("sourcesOnly") ?? "false";
+
+ const chatHistory = (await req.json()) as {
+ chatHistory: ChatHistory[];
+ };
+
+ console.log("CHathistory", chatHistory);
+
+ if (!query) {
+ return new Response(JSON.stringify({ message: "Invalid query" }), {
+ status: 400,
+ });
+ }
+
+ const resp = await fetch(
+ `https://cf-ai-backend.dhravya.workers.dev/chat?q=${query}&user=${session.user.email ?? session.user.name}&sourcesOnly=${sourcesOnly}&spaces=${spaces}`,
+ {
+ headers: {
+ "X-Custom-Auth-Key": env.BACKEND_SECURITY_KEY,
+ },
+ method: "POST",
+ body: JSON.stringify({
+ chatHistory: chatHistory.chatHistory ?? [],
+ }),
+ },
+ );
+
+ console.log(resp.status);
+ console.log(resp.statusText);
+
+ if (resp.status !== 200 || !resp.ok) {
+ const errorData = await resp.json();
+ console.log(errorData);
+ return new Response(
+ JSON.stringify({ message: "Error in CF function", error: errorData }),
+ { status: resp.status },
+ );
+ }
+
+ // Stream the response back to the client
+ const { readable, writable } = new TransformStream();
+ resp && resp.body!.pipeTo(writable);
+
+ return new Response(readable, { status: 200 });
+}
diff --git a/apps/web/src/app/api/me/route.ts b/apps/web/src/app/api/me/route.ts
index a2e713e1..6d269872 100644
--- a/apps/web/src/app/api/me/route.ts
+++ b/apps/web/src/app/api/me/route.ts
@@ -7,19 +7,42 @@ import { env } from "@/env";
export const runtime = "edge";
export async function GET(req: NextRequest) {
- const token = req.cookies.get("next-auth.session-token")?.value ?? req.cookies.get("__Secure-authjs.session-token")?.value ?? req.cookies.get("authjs.session-token")?.value ?? req.headers.get("Authorization")?.replace("Bearer ", "");
+ const token =
+ req.cookies.get("next-auth.session-token")?.value ??
+ req.cookies.get("__Secure-authjs.session-token")?.value ??
+ req.cookies.get("authjs.session-token")?.value ??
+ req.headers.get("Authorization")?.replace("Bearer ", "");
- const session = await db.select().from(sessions).where(eq(sessions.sessionToken, token!))
+ const session = await db
+ .select()
+ .from(sessions)
+ .where(eq(sessions.sessionToken, token!));
- if (!session || session.length === 0) {
- return new Response(JSON.stringify({ message: "Invalid Key, session not found." }), { status: 404 });
- }
+ if (!session || session.length === 0) {
+ return new Response(
+ JSON.stringify({ message: "Invalid Key, session not found." }),
+ { status: 404 },
+ );
+ }
- const user = await db.select().from(users).where(eq(users.id, session[0].userId)).limit(1)
+ const user = await db
+ .select()
+ .from(users)
+ .where(eq(users.id, session[0].userId))
+ .limit(1);
- if (!user || user.length === 0) {
- return NextResponse.json({ message: "Invalid Key, session not found." }, { status: 404 });
- }
+ if (!user || user.length === 0) {
+ return NextResponse.json(
+ { message: "Invalid Key, session not found." },
+ { status: 404 },
+ );
+ }
- return new Response(JSON.stringify({ message: "OK", data: { session: session[0], user: user[0] } }), { status: 200 });
-} \ No newline at end of file
+ return new Response(
+ JSON.stringify({
+ message: "OK",
+ data: { session: session[0], user: user[0] },
+ }),
+ { status: 200 },
+ );
+}
diff --git a/apps/web/src/app/api/query/route.ts b/apps/web/src/app/api/query/route.ts
index 28f441bc..02bb79da 100644
--- a/apps/web/src/app/api/query/route.ts
+++ b/apps/web/src/app/api/query/route.ts
@@ -7,46 +7,72 @@ import { env } from "@/env";
export const runtime = "edge";
export async function GET(req: NextRequest) {
- const token = req.cookies.get("next-auth.session-token")?.value ?? req.cookies.get("__Secure-authjs.session-token")?.value ?? req.cookies.get("authjs.session-token")?.value ?? req.headers.get("Authorization")?.replace("Bearer ", "");
+ const token =
+ req.cookies.get("next-auth.session-token")?.value ??
+ req.cookies.get("__Secure-authjs.session-token")?.value ??
+ req.cookies.get("authjs.session-token")?.value ??
+ req.headers.get("Authorization")?.replace("Bearer ", "");
- const sessionData = await db.select().from(sessions).where(eq(sessions.sessionToken, token!))
+ const sessionData = await db
+ .select()
+ .from(sessions)
+ .where(eq(sessions.sessionToken, token!));
- if (!sessionData || sessionData.length === 0) {
- return new Response(JSON.stringify({ message: "Invalid Key, session not found." }), { status: 404 });
- }
+ if (!sessionData || sessionData.length === 0) {
+ return new Response(
+ JSON.stringify({ message: "Invalid Key, session not found." }),
+ { status: 404 },
+ );
+ }
- const user = await db.select().from(users).where(eq(users.id, sessionData[0].userId)).limit(1)
+ const user = await db
+ .select()
+ .from(users)
+ .where(eq(users.id, sessionData[0].userId))
+ .limit(1);
- if (!user || user.length === 0) {
- return NextResponse.json({ message: "Invalid Key, session not found." }, { status: 404 });
- }
+ if (!user || user.length === 0) {
+ return NextResponse.json(
+ { message: "Invalid Key, session not found." },
+ { status: 404 },
+ );
+ }
- const session = { session: sessionData[0], user: user[0] }
+ const session = { session: sessionData[0], user: user[0] };
- const query = new URL(req.url).searchParams.get("q");
- const sourcesOnly = new URL(req.url).searchParams.get("sourcesOnly") ?? "false";
+ const query = new URL(req.url).searchParams.get("q");
+ const sourcesOnly =
+ new URL(req.url).searchParams.get("sourcesOnly") ?? "false";
- if (!query) {
- return new Response(JSON.stringify({ message: "Invalid query" }), { status: 400 });
- }
+ if (!query) {
+ return new Response(JSON.stringify({ message: "Invalid query" }), {
+ status: 400,
+ });
+ }
- const resp = await fetch(`https://cf-ai-backend.dhravya.workers.dev/query?q=${query}&user=${session.user.email ?? session.user.name}&sourcesOnly=${sourcesOnly}`, {
- headers: {
- "X-Custom-Auth-Key": env.BACKEND_SECURITY_KEY,
- }
- })
+ const resp = await fetch(
+ `https://cf-ai-backend.dhravya.workers.dev/query?q=${query}&user=${session.user.email ?? session.user.name}&sourcesOnly=${sourcesOnly}`,
+ {
+ headers: {
+ "X-Custom-Auth-Key": env.BACKEND_SECURITY_KEY,
+ },
+ },
+ );
- console.log(resp.status)
+ console.log(resp.status);
- if (resp.status !== 200 || !resp.ok) {
- const errorData = await resp.json();
- console.log(errorData)
- return new Response(JSON.stringify({ message: "Error in CF function", error: errorData }), { status: resp.status });
- }
+ if (resp.status !== 200 || !resp.ok) {
+ const errorData = await resp.json();
+ console.log(errorData);
+ return new Response(
+ JSON.stringify({ message: "Error in CF function", error: errorData }),
+ { status: resp.status },
+ );
+ }
- // Stream the response back to the client
- const { readable, writable } = new TransformStream();
- resp && resp.body!.pipeTo(writable);
+ // Stream the response back to the client
+ const { readable, writable } = new TransformStream();
+ resp && resp.body!.pipeTo(writable);
- return new Response(readable, { status: 200 });
-} \ No newline at end of file
+ return new Response(readable, { status: 200 });
+}
diff --git a/apps/web/src/app/api/store/route.ts b/apps/web/src/app/api/store/route.ts
index 06db08b9..ebe23077 100644
--- a/apps/web/src/app/api/store/route.ts
+++ b/apps/web/src/app/api/store/route.ts
@@ -1,6 +1,12 @@
import { db } from "@/server/db";
import { and, eq } from "drizzle-orm";
-import { contentToSpace, sessions, storedContent, users, space } from "@/server/db/schema";
+import {
+ contentToSpace,
+ sessions,
+ storedContent,
+ users,
+ space,
+} from "@/server/db/schema";
import { type NextRequest, NextResponse } from "next/server";
import { env } from "@/env";
import { getMetaData } from "@/server/helpers";
@@ -8,94 +14,123 @@ import { getMetaData } from "@/server/helpers";
export const runtime = "edge";
export async function POST(req: NextRequest) {
- const token = req.cookies.get("next-auth.session-token")?.value ?? req.cookies.get("__Secure-authjs.session-token")?.value ?? req.cookies.get("authjs.session-token")?.value ?? req.headers.get("Authorization")?.replace("Bearer ", "");
-
- if (!token) {
- return new Response(JSON.stringify({ message: "Invalid Key, session not found." }), { status: 404 });
- }
-
- const sessionData = await db.select().from(sessions).where(eq(sessions.sessionToken, token!))
-
- if (!sessionData || sessionData.length === 0) {
- return new Response(JSON.stringify({ message: "Invalid Key, session not found." }), { status: 404 });
- }
-
- const user = await db.select().from(users).where(eq(users.id, sessionData[0].userId)).limit(1)
-
- if (!user || user.length === 0) {
- return NextResponse.json({ message: "Invalid Key, session not found." }, { status: 404 });
- }
-
- const session = { session: sessionData[0], user: user[0] }
-
- const data = await req.json() as {
- pageContent: string,
- url: string,
- space?: string
- };
-
- const metadata = await getMetaData(data.url);
-
-
- let id: number | undefined = undefined;
-
- let storeToSpace = data.space
-
- if (!storeToSpace) {
- storeToSpace = 'all'
- }
-
- const storedContentId = await db.insert(storedContent).values({
- content: data.pageContent,
- title: metadata.title,
- description: metadata.description,
- url: data.url,
- baseUrl: metadata.baseUrl,
- image: metadata.image,
- savedAt: new Date(),
- user: session.user.id
- })
-
- id = storedContentId.meta.last_row_id;
-
- if (!id) {
- return NextResponse.json({ message: "Error", error: "Error in CF function" }, { status: 500 });
- }
-
- let spaceID = 0;
-
- const spaceData = await db.select().from(space).where(and(eq(space.name, storeToSpace), eq(space.user, session.user.id))).limit(1)
- spaceID = spaceData[0]?.id
-
- if (!spaceData || spaceData.length === 0) {
- const spaceId = await db.insert(space).values({
- name: storeToSpace,
- user: session.user.id
- })
- spaceID = spaceId.meta.last_row_id;
- }
-
- await db.insert(contentToSpace).values({
- contentId: id as number,
- spaceId: spaceID
- })
-
- const res = await Promise.race([
- fetch("https://cf-ai-backend.dhravya.workers.dev/add", {
- method: "POST",
- headers: {
- "X-Custom-Auth-Key": env.BACKEND_SECURITY_KEY,
- },
- body: JSON.stringify({ ...data, user: session.user.email }),
- }),
- new Promise((_, reject) =>
- setTimeout(() => reject(new Error('Request timed out')), 40000)
- )
- ]) as Response
-
- if (res.status !== 200) {
- return NextResponse.json({ message: "Error", error: "Error in CF function" }, { status: 500 });
- }
-
- return NextResponse.json({ message: "OK", data: "Success" }, { status: 200 });
-} \ No newline at end of file
+ const token =
+ req.cookies.get("next-auth.session-token")?.value ??
+ req.cookies.get("__Secure-authjs.session-token")?.value ??
+ req.cookies.get("authjs.session-token")?.value ??
+ req.headers.get("Authorization")?.replace("Bearer ", "");
+
+ if (!token) {
+ return new Response(
+ JSON.stringify({ message: "Invalid Key, session not found." }),
+ { status: 404 },
+ );
+ }
+
+ const sessionData = await db
+ .select()
+ .from(sessions)
+ .where(eq(sessions.sessionToken, token!));
+
+ if (!sessionData || sessionData.length === 0) {
+ return new Response(
+ JSON.stringify({ message: "Invalid Key, session not found." }),
+ { status: 404 },
+ );
+ }
+
+ const user = await db
+ .select()
+ .from(users)
+ .where(eq(users.id, sessionData[0].userId))
+ .limit(1);
+
+ if (!user || user.length === 0) {
+ return NextResponse.json(
+ { message: "Invalid Key, session not found." },
+ { status: 404 },
+ );
+ }
+
+ const session = { session: sessionData[0], user: user[0] };
+
+ const data = (await req.json()) as {
+ pageContent: string;
+ url: string;
+ space?: string;
+ };
+
+ const metadata = await getMetaData(data.url);
+
+ let id: number | undefined = undefined;
+
+ let storeToSpace = data.space;
+
+ if (!storeToSpace) {
+ storeToSpace = "all";
+ }
+
+ const storedContentId = await db.insert(storedContent).values({
+ content: data.pageContent,
+ title: metadata.title,
+ description: metadata.description,
+ url: data.url,
+ baseUrl: metadata.baseUrl,
+ image: metadata.image,
+ savedAt: new Date(),
+ user: session.user.id,
+ });
+
+ id = storedContentId.meta.last_row_id;
+
+ if (!id) {
+ return NextResponse.json(
+ { message: "Error", error: "Error in CF function" },
+ { status: 500 },
+ );
+ }
+
+ let spaceID = 0;
+
+ const spaceData = await db
+ .select()
+ .from(space)
+ .where(and(eq(space.name, storeToSpace), eq(space.user, session.user.id)))
+ .limit(1);
+ spaceID = spaceData[0]?.id;
+
+ if (!spaceData || spaceData.length === 0) {
+ const spaceId = await db.insert(space).values({
+ name: storeToSpace,
+ user: session.user.id,
+ });
+ spaceID = spaceId.meta.last_row_id;
+ }
+
+ await db.insert(contentToSpace).values({
+ contentId: id as number,
+ spaceId: spaceID,
+ });
+
+ const res = (await Promise.race([
+ fetch("https://cf-ai-backend.dhravya.workers.dev/add", {
+ method: "POST",
+ headers: {
+ "X-Custom-Auth-Key": env.BACKEND_SECURITY_KEY,
+ },
+ body: JSON.stringify({ ...data, user: session.user.email }),
+ }),
+ new Promise((_, reject) =>
+ setTimeout(() => reject(new Error("Request timed out")), 40000),
+ ),
+ ])) as Response;
+
+ if (res.status !== 200) {
+ return NextResponse.json(
+ { message: "Error", error: "Error in CF function" },
+ { status: 500 },
+ );
+ }
+
+ return NextResponse.json({ message: "OK", data: "Success" }, { status: 200 });
+}