-
-
Save gmdias727/c4fc06220ef72e0031c9adadfb295f1b to your computer and use it in GitHub Desktop.
TS Seed Script: Drizzle ORM + Zod + Faker (Minimal)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// tsx seed.ts | |
import { faker } from '@faker-js/faker'; | |
import { pgTable, text, varchar, timestamp } from 'drizzle-orm/pg-core'; | |
import { drizzle, PostgresJsDatabase } from 'drizzle-orm/postgres-js'; | |
import { createInsertSchema } from 'drizzle-zod'; | |
import { customAlphabet } from 'nanoid'; | |
import postgres from 'postgres'; | |
import { z } from 'zod'; | |
import '#env.ts'; | |
const alphabet = '0123456789abcdefghijklmnopqrstuvwxyz'; | |
const length = 14; | |
const nanoid = customAlphabet(alphabet, length); | |
function generatePublicId() { | |
return nanoid(); | |
} | |
const queryClient = postgres(process.env.DATABASE_DIRECT_URL || ''); | |
const db: PostgresJsDatabase = drizzle(queryClient, { | |
logger: true, | |
}); | |
const users = pgTable('users', { | |
id: varchar('id', { length: 14 }).primaryKey(), | |
name: text('name').notNull(), | |
email: text('email').notNull().unique(), | |
createdAt: timestamp('created_at').notNull().defaultNow(), | |
updatedAt: timestamp('updated_at').notNull().defaultNow(), | |
}); | |
const insertUserSchema = createInsertSchema(users, { | |
email: (schema) => schema.email.email('Email address is not valid'), | |
}); | |
type UserToBeInserted = z.infer<typeof insertUserSchema>; | |
const generateUserRows = (count: number): UserToBeInserted[] => { | |
const rows: UserToBeInserted[] = []; | |
for (let i = 0; i < count; i++) { | |
rows.push({ | |
id: generatePublicId(), | |
email: faker.internet.email(), | |
name: `${faker.person.firstName()} ${faker.person.lastName()}`, | |
}); | |
} | |
return rows; | |
}; | |
async function seed() { | |
console.log('Seeding...'); | |
console.time('DB has been seeded!'); | |
// database teardown | |
await db.delete(users); | |
// database setup | |
const newUserRows = generateUserRows(100); | |
await db.insert(users).values(newUserRows).returning(); | |
} | |
seed() | |
.catch((e) => { | |
console.error(e); | |
process.exit(1); | |
}) | |
.finally(async () => { | |
console.log('Seeding done!'); | |
process.exit(0); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment