From c332a1b6f146bdedde35f895dc1484665e1fdf08 Mon Sep 17 00:00:00 2001 From: Jared Palmer Date: Fri, 2 Jun 2023 11:57:44 -0400 Subject: [PATCH] Try drizzle --- app/api/chat/route.ts | 37 ++++++++------- app/chat.tsx | 3 +- app/chat/[id]/page.tsx | 25 ++++------ app/page.tsx | 4 +- app/sidebar.tsx | 23 +++++---- lib/db/migrate.ts | 1 + lib/db/migrations/0002_striped_purifiers.sql | 1 + lib/db/migrations/meta/0002_snapshot.json | 49 ++++++++++++++++++++ lib/db/migrations/meta/_journal.json | 7 +++ lib/db/schema.ts | 4 +- 10 files changed, 107 insertions(+), 47 deletions(-) create mode 100644 lib/db/migrations/0002_striped_purifiers.sql create mode 100644 lib/db/migrations/meta/0002_snapshot.json diff --git a/app/api/chat/route.ts b/app/api/chat/route.ts index 10c8031..1eb6911 100644 --- a/app/api/chat/route.ts +++ b/app/api/chat/route.ts @@ -10,13 +10,13 @@ export const POST = auth(async function POST(req: Request) { const json = await req.json(); // @ts-ignore console.log(req.auth); // todo fix types - + const messages = json.messages.map((m: any) => ({ + content: m.content, + role: m.role, + })); const res = await openai.createChatCompletion({ model: "gpt-3.5-turbo", - messages: json.messages.map((m: any) => ({ - content: m.content, - role: m.role, - })), + messages, temperature: 0.7, top_p: 1, frequency_penalty: 1, @@ -33,23 +33,26 @@ export const POST = auth(async function POST(req: Request) { } const title = json.messages[0].content.substring(0, 20); const payload = { - id: json.id ?? crypto.randomUUID(), + id: crypto.randomUUID(), title, userId: (req as any).auth?.user?.email, - messages: json.messages.concat({ - content: completion, - role: "assistant", - id: nanoid(), - }), + messages: [ + ...messages, + { + content: completion, + role: "assistant", + }, + ], }; - await db + const chat = await db .insert(chats) .values(payload) - .onConflictDoUpdate({ - target: json.id, - set: payload, - }) - .execute(); + // .onConflictDoUpdate({ + // target: payload.id, + // set: payload, + // }) + .returning(); + console.log(chat); }, }); diff --git a/app/chat.tsx b/app/chat.tsx index 9d69ee5..16d3870 100644 --- a/app/chat.tsx +++ b/app/chat.tsx @@ -1,10 +1,9 @@ "use client"; -import { type Message } from "@prisma/client"; import { useRouter } from "next/navigation"; import { ChatList } from "./chat-list"; import { Prompt } from "./prompt"; -import { useChat } from "ai-connector"; +import { useChat, type Message } from "ai-connector"; export interface ChatProps { // create?: (input: string) => Chat | undefined; diff --git a/app/chat/[id]/page.tsx b/app/chat/[id]/page.tsx index 51331ce..51358d7 100644 --- a/app/chat/[id]/page.tsx +++ b/app/chat/[id]/page.tsx @@ -1,10 +1,11 @@ import { Sidebar } from "@/app/sidebar"; -import { prisma } from "@/lib/prisma"; -import { Chat } from "../../chat"; import { type Metadata } from "next"; import { auth } from "@/auth"; - +import { db, chats } from "@/lib/db/schema"; +import { eq } from "drizzle-orm"; +import { Chat } from "@/app/chat"; +import { Message } from "ai-connector"; export interface ChatPageProps { params: { id: string; @@ -14,10 +15,8 @@ export interface ChatPageProps { export async function generateMetadata({ params, }: ChatPageProps): Promise { - const chat = await prisma.chat.findFirst({ - where: { - id: params.id, - }, + const chat = await db.query.chats.findFirst({ + where: eq(chats.id, params.id), }); return { title: chat?.title.slice(0, 50) ?? "Chat", @@ -30,14 +29,10 @@ export const preferredRegion = "home"; export const dynamic = "force-dynamic"; export default async function ChatPage({ params }: ChatPageProps) { const session = await auth(); - const chat = await prisma.chat.findFirst({ - where: { - id: params.id, - }, - include: { - messages: true, - }, + const chat = await db.query.chats.findFirst({ + where: eq(chats.id, params.id), }); + if (!chat) { throw new Error("Chat not found"); } @@ -46,7 +41,7 @@ export default async function ChatPage({ params }: ChatPageProps) {
- +
); diff --git a/app/page.tsx b/app/page.tsx index 7dec5b3..c366367 100644 --- a/app/page.tsx +++ b/app/page.tsx @@ -2,10 +2,8 @@ import { Chat } from "./chat"; import { Sidebar } from "./sidebar"; import { auth } from "@/auth"; -// Prisma does not support Edge without the Data Proxy currently -export const runtime = "nodejs"; // default +export const runtime = "edge"; // default export const preferredRegion = "home"; -export const dynamic = "force-dynamic"; export default async function IndexPage() { const session = await auth(); diff --git a/app/sidebar.tsx b/app/sidebar.tsx index ed61d7a..ebe0963 100644 --- a/app/sidebar.tsx +++ b/app/sidebar.tsx @@ -1,14 +1,14 @@ -import { NextChatLogo } from "@/components/ui/nextchat-logo"; import { Login } from "@/components/ui/login"; +import { NextChatLogo } from "@/components/ui/nextchat-logo"; import { UserMenu } from "@/components/ui/user-menu"; -import { prisma } from "@/lib/prisma"; -import { type Session } from "@auth/nextjs/types"; +import { db, chats } from "@/lib/db/schema"; import { cn } from "@/lib/utils"; +import { type Session } from "@auth/nextjs/types"; +import { eq } from "drizzle-orm"; import { Plus } from "lucide-react"; -import Link from "next/link"; import { unstable_cache } from "next/cache"; +import Link from "next/link"; import { SidebarItem } from "./sidebar-item"; -import { db } from "@/lib/db/schema"; export interface SidebarProps { session?: Session; @@ -59,9 +59,16 @@ export function Sidebar({ session, newChat }: SidebarProps) { Sidebar.displayName = "Sidebar"; async function SidebarList({ session }: { session?: Session }) { - const chats = await ( + const results: any[] = await ( await unstable_cache( - () => db.query.chats.findMany({}), + () => + db.query.chats.findMany({ + columns: { + id: true, + title: true, + }, + where: eq(chats.userId, session?.user?.email || ""), + }), // @ts-ignore [session?.user?.id || ""], { @@ -70,7 +77,7 @@ async function SidebarList({ session }: { session?: Session }) { ) )(); - return chats.map((c) => ( + return results.map((c) => ( )); } diff --git a/lib/db/migrate.ts b/lib/db/migrate.ts index cfbe862..a67bd90 100644 --- a/lib/db/migrate.ts +++ b/lib/db/migrate.ts @@ -4,6 +4,7 @@ import * as dotenv from "dotenv"; dotenv.config(); +// @ts-ignore migrate(db, { migrationsFolder: "lib/db/migrations", }) diff --git a/lib/db/migrations/0002_striped_purifiers.sql b/lib/db/migrations/0002_striped_purifiers.sql new file mode 100644 index 0000000..b9db043 --- /dev/null +++ b/lib/db/migrations/0002_striped_purifiers.sql @@ -0,0 +1 @@ +ALTER TABLE "chats" ADD COLUMN "messages" json DEFAULT '{}'::json NOT NULL; \ No newline at end of file diff --git a/lib/db/migrations/meta/0002_snapshot.json b/lib/db/migrations/meta/0002_snapshot.json new file mode 100644 index 0000000..6f5b1cb --- /dev/null +++ b/lib/db/migrations/meta/0002_snapshot.json @@ -0,0 +1,49 @@ +{ + "version": "5", + "dialect": "pg", + "id": "e3f4035a-a940-4529-b037-1737e178d88b", + "prevId": "e8eef642-fc25-4737-8e75-5ad1e8c53b84", + "tables": { + "chats": { + "name": "chats", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "role": { + "name": "role", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "userId": { + "name": "userId", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "messages": { + "name": "messages", + "type": "json", + "primaryKey": false, + "notNull": true, + "default": "'{}'::json" + } + }, + "indexes": {}, + "foreignKeys": {}, + "compositePrimaryKeys": {} + } + }, + "enums": {}, + "schemas": {}, + "_meta": { + "schemas": {}, + "tables": {}, + "columns": {} + } +} \ No newline at end of file diff --git a/lib/db/migrations/meta/_journal.json b/lib/db/migrations/meta/_journal.json index d83e0fb..e6695c1 100644 --- a/lib/db/migrations/meta/_journal.json +++ b/lib/db/migrations/meta/_journal.json @@ -15,6 +15,13 @@ "when": 1685719963202, "tag": "0001_naive_gunslinger", "breakpoints": false + }, + { + "idx": 2, + "version": "5", + "when": 1685720130302, + "tag": "0002_striped_purifiers", + "breakpoints": false } ] } \ No newline at end of file diff --git a/lib/db/schema.ts b/lib/db/schema.ts index 7f983f5..28fafa9 100644 --- a/lib/db/schema.ts +++ b/lib/db/schema.ts @@ -1,5 +1,5 @@ import { sql } from "@vercel/postgres"; -import { pgTable, text } from "drizzle-orm/pg-core"; +import { json, pgTable, text } from "drizzle-orm/pg-core"; import { drizzle } from "drizzle-orm/vercel-postgres"; // const connection = createPool({ connectionString: process.env.POSTGRES_URL }); @@ -8,7 +8,7 @@ export const chats = pgTable("chats", { id: text("id").notNull().primaryKey(), title: text("role").notNull(), userId: text("userId").notNull(), - // messages: json("messages").notNull().default({}), + messages: json("messages").notNull().default({}), // .references(() => users.id), });