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,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`;
};