Refactor to use hooks (#436)
This commit is contained in:
parent
124efca9a1
commit
cb60f8b143
139 changed files with 8871 additions and 8726 deletions
32
db/migrate.ts
Normal file
32
db/migrate.ts
Normal file
|
|
@ -0,0 +1,32 @@
|
|||
import { config } from "dotenv";
|
||||
import { drizzle } from "drizzle-orm/postgres-js";
|
||||
import { migrate } from "drizzle-orm/postgres-js/migrator";
|
||||
import postgres from "postgres";
|
||||
|
||||
config({
|
||||
path: ".env.local",
|
||||
});
|
||||
|
||||
const runMigrate = async () => {
|
||||
if (!process.env.POSTGRES_URL) {
|
||||
throw new Error("POSTGRES_URL is not defined");
|
||||
}
|
||||
|
||||
const connection = postgres(process.env.POSTGRES_URL, { max: 1 });
|
||||
const db = drizzle(connection);
|
||||
|
||||
console.log("⏳ Running migrations...");
|
||||
|
||||
const start = Date.now();
|
||||
await migrate(db, { migrationsFolder: "./lib/drizzle" });
|
||||
const end = Date.now();
|
||||
|
||||
console.log("✅ Migrations completed in", end - start, "ms");
|
||||
process.exit(0);
|
||||
};
|
||||
|
||||
runMigrate().catch((err) => {
|
||||
console.error("❌ Migration failed");
|
||||
console.error(err);
|
||||
process.exit(1);
|
||||
});
|
||||
100
db/queries.ts
Normal file
100
db/queries.ts
Normal file
|
|
@ -0,0 +1,100 @@
|
|||
"server-only";
|
||||
|
||||
import { genSaltSync, hashSync } from "bcrypt-ts";
|
||||
import { desc, eq } from "drizzle-orm";
|
||||
import { drizzle } from "drizzle-orm/postgres-js";
|
||||
import postgres from "postgres";
|
||||
|
||||
import { user, chat, User } from "./schema";
|
||||
|
||||
// Optionally, if not using email/pass login, you can
|
||||
// use the Drizzle adapter for Auth.js / NextAuth
|
||||
// https://authjs.dev/reference/adapter/drizzle
|
||||
let client = postgres(`${process.env.POSTGRES_URL!}?sslmode=require`);
|
||||
let db = drizzle(client);
|
||||
|
||||
export async function getUser(email: string): Promise<Array<User>> {
|
||||
try {
|
||||
return await db.select().from(user).where(eq(user.email, email));
|
||||
} catch (error) {
|
||||
console.error("Failed to get user from database");
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
export async function createUser(email: string, password: string) {
|
||||
let salt = genSaltSync(10);
|
||||
let hash = hashSync(password, salt);
|
||||
|
||||
try {
|
||||
return await db.insert(user).values({ email, password: hash });
|
||||
} catch (error) {
|
||||
console.error("Failed to create user in database");
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
export async function saveChat({
|
||||
id,
|
||||
messages,
|
||||
userId,
|
||||
}: {
|
||||
id: string;
|
||||
messages: any;
|
||||
userId: string;
|
||||
}) {
|
||||
try {
|
||||
const selectedChats = await db.select().from(chat).where(eq(chat.id, id));
|
||||
|
||||
if (selectedChats.length > 0) {
|
||||
return await db
|
||||
.update(chat)
|
||||
.set({
|
||||
messages: JSON.stringify(messages),
|
||||
})
|
||||
.where(eq(chat.id, id));
|
||||
}
|
||||
|
||||
return await db.insert(chat).values({
|
||||
id,
|
||||
createdAt: new Date(),
|
||||
messages: JSON.stringify(messages),
|
||||
userId,
|
||||
});
|
||||
} catch (error) {
|
||||
console.error("Failed to save chat in database");
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
export async function deleteChatById({ id }: { id: string }) {
|
||||
try {
|
||||
return await db.delete(chat).where(eq(chat.id, id));
|
||||
} catch (error) {
|
||||
console.error("Failed to delete chat by id from database");
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
export async function getChatsByUserId({ id }: { id: string }) {
|
||||
try {
|
||||
return await db
|
||||
.select()
|
||||
.from(chat)
|
||||
.where(eq(chat.userId, id))
|
||||
.orderBy(desc(chat.createdAt));
|
||||
} catch (error) {
|
||||
console.error("Failed to get chats by user from database");
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
export async function getChatById({ id }: { id: string }) {
|
||||
try {
|
||||
const [selectedChat] = await db.select().from(chat).where(eq(chat.id, id));
|
||||
return selectedChat;
|
||||
} catch (error) {
|
||||
console.error("Failed to get chat by id from database");
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
24
db/schema.ts
Normal file
24
db/schema.ts
Normal file
|
|
@ -0,0 +1,24 @@
|
|||
import { Message } from "ai";
|
||||
import { InferSelectModel } from "drizzle-orm";
|
||||
import { pgTable, varchar, timestamp, json, uuid } from "drizzle-orm/pg-core";
|
||||
|
||||
export const user = pgTable("User", {
|
||||
id: uuid("id").primaryKey().notNull().defaultRandom(),
|
||||
email: varchar("email", { length: 64 }).notNull(),
|
||||
password: varchar("password", { length: 64 }),
|
||||
});
|
||||
|
||||
export type User = InferSelectModel<typeof user>;
|
||||
|
||||
export const chat = pgTable("Chat", {
|
||||
id: uuid("id").primaryKey().notNull().defaultRandom(),
|
||||
createdAt: timestamp("createdAt").notNull(),
|
||||
messages: json("messages").notNull(),
|
||||
userId: uuid("userId")
|
||||
.notNull()
|
||||
.references(() => user.id),
|
||||
});
|
||||
|
||||
export type Chat = Omit<InferSelectModel<typeof chat>, "messages"> & {
|
||||
messages: Array<Message>;
|
||||
};
|
||||
Loading…
Add table
Add a link
Reference in a new issue