Switch to @vercel/kv (#7)

This commit is contained in:
Jared Palmer 2023-06-02 15:17:39 -04:00 committed by GitHub
commit 8cc402ac2a
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
20 changed files with 188 additions and 1079 deletions

View file

@ -1,20 +1,5 @@
{
"$schema": "https://json.schemastore.org/eslintrc",
"root": true,
"extends": ["next/core-web-vitals", "prettier"],
"rules": {
"@next/next/no-html-link-for-pages": "off",
"react/jsx-key": "off"
},
"settings": {
"next": {
"rootDir": ["./"]
}
},
"overrides": [
{
"files": ["*.ts", "*.tsx"],
"parser": "@typescript-eslint/parser"
}
]
"extends": ["next/core-web-vitals", "prettier"]
}

View file

@ -1,8 +1,6 @@
"use server";
import { auth } from "@/auth";
import { chats, db } from "@/lib/db/schema";
import { and, eq } from "drizzle-orm";
import { kv } from "@vercel/kv";
import { revalidatePath } from "next/cache";
export async function removeChat({
@ -14,18 +12,15 @@ export async function removeChat({
userId: string;
path: string;
}) {
// @todo next-auth doesn't work in server actions yet
// @todo next-auth@v5 doesn't work in server actions yet
// const session = await auth();
// const userId = session?.user?.email;
// if (!userId || !id) {
// throw new Error("Unauthorized");
// }
await db
.delete(chats)
.where(and(eq(chats.id, id), eq(chats.userId, userId)))
.execute();
const uid = await kv.hget<string>(`chat:${id}`, "userId");
if (uid !== userId) {
throw new Error("Unauthorized");
}
await kv.del(`chat:${id}`);
await kv.zrem(`user:chat:${userId}`, `chat:${id}`);
revalidatePath("/");
revalidatePath("/chat/[id]");

View file

@ -1,5 +1,6 @@
import { auth } from "@/auth";
import { chats, db } from "@/lib/db/schema";
import { kv } from "@vercel/kv";
import { nanoid } from "@/lib/utils";
import { OpenAIStream, StreamingTextResponse } from "ai-connector";
import { Configuration, OpenAIApi } from "openai-edge";
@ -41,10 +42,14 @@ export const POST = auth(async function POST(req: Request) {
return;
}
const title = json.messages[0].content.substring(0, 20);
const userId = (req as any).auth?.user?.email;
const id = json.id ?? nanoid();
const createdAt = Date.now();
const payload = {
id: crypto.randomUUID(),
id,
title,
userId: (req as any).auth?.user?.email,
userId,
createdAt,
messages: [
...messages,
{
@ -53,15 +58,11 @@ export const POST = auth(async function POST(req: Request) {
},
],
};
const chat = await db
.insert(chats)
.values(payload)
// .onConflictDoUpdate({
// target: payload.id,
// set: payload,
// })
.returning();
console.log(chat);
await kv.hmset(`chat:${id}`, payload);
await kv.zadd(`user:chat:${userId}`, {
score: createdAt,
member: `chat:${id}`,
});
},
});

View file

@ -1,10 +1,11 @@
import { Sidebar } from "@/app/sidebar";
import { type Metadata } from "next";
import { auth } from "@/auth";
import { db, chats } from "@/lib/db/schema";
import { eq } from "drizzle-orm";
import { type Metadata } from "next";
import { Chat } from "@/app/chat";
import { type Chat as ChatType } from "@/lib/types";
import { kv } from "@vercel/kv";
import { Message } from "ai-connector";
export const runtime = "edge";
@ -18,9 +19,8 @@ export interface ChatPageProps {
export async function generateMetadata({
params,
}: ChatPageProps): Promise<Metadata> {
const chat = await db.query.chats.findFirst({
where: eq(chats.id, params.id),
});
const session = await auth();
const chat = await getChat(params.id, session?.user?.email ?? "");
return {
title: chat?.title.slice(0, 50) ?? "Chat",
};
@ -28,13 +28,7 @@ export async function generateMetadata({
export default async function ChatPage({ params }: ChatPageProps) {
const session = await auth();
const chat = await db.query.chats.findFirst({
where: eq(chats.id, params.id),
});
if (!chat) {
throw new Error("Chat not found");
}
const chat = await getChat(params.id, session?.user?.email ?? "");
return (
<div className="relative flex h-full w-full overflow-hidden">
@ -47,3 +41,16 @@ export default async function ChatPage({ params }: ChatPageProps) {
}
ChatPage.displayName = "ChatPage";
async function getChat(id: string, userId: string) {
const chat = await kv.hgetall<ChatType>(`chat:${id}`);
if (!chat) {
throw new Error("Not found");
}
if (userId && chat.userId !== userId) {
throw new Error("Unauthorized");
}
return chat;
}

View file

@ -1,15 +1,14 @@
import { Login } from "@/components/ui/login";
import { NextChatLogo } from "@/components/ui/nextchat-logo";
import { UserMenu } from "@/components/ui/user-menu";
import { db, chats } from "@/lib/db/schema";
import { kv } from "@vercel/kv";
import { Chat } from "@/lib/types";
import { cn } from "@/lib/utils";
import { type Session } from "@auth/nextjs/types";
import { eq } from "drizzle-orm";
import { Plus } from "lucide-react";
import { unstable_cache } from "next/cache";
import Link from "next/link";
import { SidebarItem } from "./sidebar-item";
import { ExternalLink } from "./external-link";
import { SidebarItem } from "./sidebar-item";
export interface SidebarProps {
session?: Session;
@ -87,23 +86,7 @@ export function Sidebar({ session, newChat }: SidebarProps) {
Sidebar.displayName = "Sidebar";
async function SidebarList({ session }: { session?: Session }) {
const results: any[] = await (
await unstable_cache(
() =>
db.query.chats.findMany({
columns: {
id: true,
title: true,
},
where: eq(chats.userId, session?.user?.email || ""),
}),
// @ts-ignore
[session?.user?.email ?? ""],
{
revalidate: 3600,
}
)
)();
const results: Chat[] = await getChats(session?.user?.email ?? "");
return results.map((c) => (
<SidebarItem
@ -115,3 +98,20 @@ async function SidebarList({ session }: { session?: Session }) {
/>
));
}
async function getChats(userId: string) {
try {
const pipeline = kv.pipeline();
const chats: string[] = await kv.zrange(`user:chat:${userId}`, 0, -1);
for (const chat of chats) {
pipeline.hgetall(chat);
}
const results = await pipeline.exec();
return results as Chat[];
} catch (error) {
return [];
}
}

View file

@ -1,6 +0,0 @@
import type { Config } from "drizzle-kit";
export default {
schema: "./lib/db/schema.ts",
out: "./lib/db/migrations",
} satisfies Config;

View file

@ -1,19 +0,0 @@
import { migrate } from "drizzle-orm/vercel-postgres/migrator";
import { db } from "./schema";
import * as dotenv from "dotenv";
dotenv.config();
// @ts-ignore
migrate(db, {
migrationsFolder: "lib/db/migrations",
})
.then(() => {
console.log("Migration was succesfull!");
})
.catch((err) => {
console.error("Migration failed:", err);
})
.finally(() => {
console.info("Migration finished");
});

View file

@ -1,6 +0,0 @@
CREATE TABLE IF NOT EXISTS "chats" (
"id" text PRIMARY KEY NOT NULL,
"role" text NOT NULL,
"userId" text NOT NULL,
"messages" json DEFAULT '{}'::json NOT NULL
);

View file

@ -1 +0,0 @@
ALTER TABLE "chats" DROP COLUMN IF EXISTS "messages";

View file

@ -1 +0,0 @@
ALTER TABLE "chats" ADD COLUMN "messages" json DEFAULT '{}'::json NOT NULL;

View file

@ -1,49 +0,0 @@
{
"version": "5",
"dialect": "pg",
"id": "3bddf21a-46a3-4ee8-8b41-bb79cb80d904",
"prevId": "00000000-0000-0000-0000-000000000000",
"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": {}
}
}

View file

@ -1,42 +0,0 @@
{
"version": "5",
"dialect": "pg",
"id": "e8eef642-fc25-4737-8e75-5ad1e8c53b84",
"prevId": "3bddf21a-46a3-4ee8-8b41-bb79cb80d904",
"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
}
},
"indexes": {},
"foreignKeys": {},
"compositePrimaryKeys": {}
}
},
"enums": {},
"schemas": {},
"_meta": {
"schemas": {},
"tables": {},
"columns": {}
}
}

View file

@ -1,49 +0,0 @@
{
"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": {}
}
}

View file

@ -1,27 +0,0 @@
{
"version": "5",
"dialect": "pg",
"entries": [
{
"idx": 0,
"version": "5",
"when": 1685719783900,
"tag": "0000_fair_groot",
"breakpoints": false
},
{
"idx": 1,
"version": "5",
"when": 1685719963202,
"tag": "0001_naive_gunslinger",
"breakpoints": false
},
{
"idx": 2,
"version": "5",
"when": 1685720130302,
"tag": "0002_striped_purifiers",
"breakpoints": false
}
]
}

View file

@ -1,56 +0,0 @@
import { sql } from "@vercel/postgres";
import { json, pgTable, text } from "drizzle-orm/pg-core";
import { drizzle } from "drizzle-orm/vercel-postgres";
// const connection = createPool({ connectionString: process.env.POSTGRES_URL });
export const chats = pgTable("chats", {
id: text("id").notNull().primaryKey(),
title: text("role").notNull(),
userId: text("userId").notNull(),
messages: json("messages").notNull().default({}),
// .references(() => users.id),
});
// export const messages = pgTable("messages", {
// id: text("id").notNull().primaryKey(),
// title: text("role").notNull(),
// chatId: text("chatId")
// .notNull()
// .references(() => chats.id),
// });
// export const chatsRelations = relations(chats, ({ many }) => ({
// // user: one(users, {
// // fields: [chats.userId],
// // references: [users.id],
// // }),
// messages: many(messages),
// }));
// export const messagesRelations = relations(messages, ({ one }) => ({
// chat: one(chats, {
// fields: [messages.chatId],
// references: [chats.id],
// }),
// }));
export const db = drizzle(sql, {
schema: {
// users,
// accounts,
// sessions,
// verificationTokens,
chats,
// chatsRelations,
// messages,
// messagesRelations,
// usersRelations,
},
});
export type DbClient = typeof db;
export type Schema = {
chats: typeof chats;
};

View file

@ -1,3 +0,0 @@
import _kv from "@vercel/kv";
export const kv = _kv;

9
lib/types.ts Normal file
View file

@ -0,0 +1,9 @@
import { type Message } from "ai-connector";
export interface Chat extends Record<string, any> {
id: string;
title: string;
createdAt: Date;
userId: string;
messages: Message[];
}

View file

@ -5,15 +5,11 @@
"scripts": {
"dev": "next dev",
"build": "next build",
"db:mg:create": "drizzle-kit generate:pg --config=drizzle.config.ts",
"db:mg:apply": "ts-node --project tsconfig.migration.json ./lib/db/migrate --config=drizzle.config.ts",
"db:check": "drizzle-kit check:pg --config=drizzle.config.ts",
"db:up": "drizzle-kit up:pg --config=drizzle.config.ts",
"start": "next start",
"lint": "next lint",
"lint:fix": "next lint --fix",
"preview": "next build && next start",
"typecheck": "tsc --noEmit",
"type-check": "tsc --noEmit",
"format:write": "prettier --write \"**/*.{ts,tsx,mdx}\" --cache",
"format:check": "prettier --check \"**/*.{ts,tsx,mdx}\" --cache"
},
@ -23,18 +19,11 @@
"@radix-ui/react-dropdown-menu": "^2.0.4",
"@vercel/analytics": "^1.0.0",
"@vercel/kv": "^0.2.1",
"@vercel/postgres": "^0.3.0",
"ai-connector": "^0.0.5",
"body-scroll-lock": "4.0.0-beta.0",
"class-variance-authority": "^0.4.0",
"clsx": "^1.2.1",
"common-tags": "^1.8.2",
"cookie": "^0.5.0",
"drizzle-orm": "^0.26.0",
"focus-trap-react": "^10.1.1",
"framer-motion": "^10.12.4",
"jose": "^4.14.4",
"jsonwebtoken": "^9.0.0",
"lucide-react": "0.216.0",
"nanoid": "^4.0.2",
"next": "13.4.5-canary.3",
@ -47,35 +36,25 @@
"react-syntax-highlighter": "^15.5.0",
"react-textarea-autosize": "^8.4.1",
"remark-gfm": "^3.0.1",
"remark-math": "^5.1.1",
"tailwind-merge": "^1.12.0",
"tailwindcss-animate": "^1.0.5",
"uuid": "^9.0.0"
"remark-math": "^5.1.1"
},
"devDependencies": {
"@ianvs/prettier-plugin-sort-imports": "^3.7.1",
"@tailwindcss/typography": "^0.5.9",
"@types/common-tags": "^1.8.1",
"@types/cookie": "^0.5.1",
"@types/jsonwebtoken": "^9.0.2",
"@types/ms": "^0.7.31",
"@types/node": "^17.0.12",
"@types/react": "^18.0.22",
"@types/react-dom": "^18.0.7",
"@types/react-syntax-highlighter": "^15.5.6",
"@typescript-eslint/parser": "^5.58.0",
"autoprefixer": "^10.4.13",
"dotenv": "^16.0.3",
"drizzle-kit": "^0.18.0",
"eslint": "^8.31.0",
"eslint-config-next": "13.4.5-canary.3",
"eslint-config-prettier": "^8.3.0",
"eslint-plugin-react": "^7.31.11",
"eslint-plugin-tailwindcss": "^3.8.0",
"postcss": "^8.4.21",
"prettier": "^2.7.1",
"tailwindcss": "^3.3.1",
"ts-node": "^10.9.1",
"tailwind-merge": "^1.12.0",
"tailwindcss-animate": "^1.0.5",
"typescript": "^4.9.3"
},
"pnpm": {

821
pnpm-lock.yaml generated

File diff suppressed because it is too large Load diff

View file

@ -1,11 +0,0 @@
{
"compilerOptions": {
"module": "CommonJS",
"moduleResolution": "Node",
"target": "ES2020",
"jsx": "react",
"strictNullChecks": true,
"strictFunctionTypes": true
},
"exclude": ["node_modules", "**/node_modules/*"]
}