feat: db init

This commit is contained in:
afiqzudinhadi 2025-06-28 17:21:09 +08:00
parent 0b1cbef59e
commit a6fc74e851
23 changed files with 1536 additions and 5553 deletions

View file

@ -0,0 +1,6 @@
import { drizzle } from "drizzle-orm/postgres-js";
import postgres from "postgres";
const client = postgres(process.env.DATABASE_URL!);
export const db = drizzle(client);

2
packages/db/src/index.ts Normal file
View file

@ -0,0 +1,2 @@
export * from "./schema/users";
export * from "./schema/products";

View file

@ -0,0 +1,6 @@
import { db } from "../database";
import { InsertProduct, product } from "../schema/products";
export async function createProduct(data: InsertProduct) {
await db.insert(product).values(data);
}

View file

@ -0,0 +1,6 @@
import { db } from "../database";
import { InsertUser, user } from "../schema/users";
export async function createUser(data: InsertUser) {
await db.insert(user).values(data);
}

View file

@ -0,0 +1,11 @@
import { timestamp } from "drizzle-orm/pg-core";
export const timestamps = {
updatedAt: timestamp("updated_at", { withTimezone: true })
.$onUpdate(() => new Date())
.notNull(),
createdAt: timestamp("created_at", { withTimezone: true })
.defaultNow()
.notNull(),
deletedAt: timestamp("deleted_at", { withTimezone: true }),
};

View file

@ -0,0 +1,15 @@
import { pgTable, serial, text, numeric, boolean } from "drizzle-orm/pg-core";
import { timestamps } from "./column.helpers";
export const product = pgTable("products", {
id: serial("id").primaryKey(),
name: text("name").notNull(),
description: text("description"),
price: numeric("price", { precision: 10, scale: 2 }).notNull(),
imageUrl: text("image_url"),
isPublished: boolean("is_published").default(false),
...timestamps,
});
export type InsertProduct = typeof product.$inferInsert;
export type SelectProduct = typeof product.$inferSelect;

View file

@ -0,0 +1,13 @@
import { pgTable, text } from "drizzle-orm/pg-core";
import { timestamps } from "./column.helpers";
export const user = pgTable("users", {
id: text("id").primaryKey(), // Clerk user ID
email: text("email").notNull(),
name: text("name"),
role: text("role").default("user").notNull(),
...timestamps,
});
export type InsertUser = typeof user.$inferInsert;
export type SelectUser = typeof user.$inferSelect;

View file

@ -0,0 +1,29 @@
import { faker } from "@faker-js/faker";
import { db } from "../database";
import { product } from "../schema/products";
import type { SeedFunction } from "./seed";
type ProductRow = {
id: number;
name: string;
description: string | null;
price: string;
imageUrl: string | null;
isPublished: boolean;
};
export const seedProducts: SeedFunction = async () => {
// generate random data for 10 people to stick into the chefs table
const data: ProductRow[] = Array.from({ length: 10 }, () => ({
id: faker.number.int({ min: 1, max: 10000 }),
name: faker.commerce.productName(),
description: faker.commerce.productDescription(),
price: faker.commerce.price({ min: 1, max: 1000, dec: 2 }),
imageUrl: faker.image.url(),
isPublished: faker.datatype.boolean(),
}));
await db.insert(product).values(data);
return `${data.length} Products seeded successfully`;
};

View file

@ -0,0 +1,52 @@
import { seedProducts } from "./products";
import { seedUsers } from "./users";
const seedDb = async () => {
// note: this function assumes we're starting with an empty database
console.log("Seeding database...");
console.log("Adding independent data...");
const res = await Promise.allSettled([
seedUsers(),
seedProducts(),
// add more independent seeding functions here
// these will run in parallel
]);
res.forEach((result) => {
if (result.status === "rejected") {
console.log("Error seeding database:", result.reason);
} else {
console.log(result.value);
}
});
// console.log("Adding related data...");
// const dependentTasks = [
// seedRecipes,
// // add more dependent tasks here, they will run in this order
// ];
// for (const task of dependentTasks) {
// try {
// const result = await task();
// console.log(result);
// } catch e {
// console.log("Error seeding database:", e);
// }
// }
console.log("Seeding complete!");
};
seedDb()
.then(() => {
console.log("Seeding complete!");
process.exit(0);
})
.catch((err) => {
console.error("Error seeding database:", err);
process.exit(1);
});
export type SeedFunction = () => Promise<string>;

View file

@ -0,0 +1,23 @@
import { faker } from "@faker-js/faker";
import { db } from "../database";
import { user } from "../schema/users";
import type { SeedFunction } from "./seed";
type UserRow = {
id: string;
name: string;
email: string;
};
export const seedUsers: SeedFunction = async () => {
// generate random data for 10 people to stick into the chefs table
const data: UserRow[] = Array.from({ length: 10 }, () => ({
id: faker.number.int({ min: 1, max: 10000 }).toString(),
name: faker.person.fullName(),
email: faker.internet.email(),
}));
await db.insert(user).values(data);
return `${data.length} Users seeded successfully`;
};