Skip to content

Instantly share code, notes, and snippets.

@andregaldino
Last active November 9, 2023 02:33
Show Gist options
  • Save andregaldino/17d291584277ee0fd3b6e700fd57135d to your computer and use it in GitHub Desktop.
Save andregaldino/17d291584277ee0fd3b6e700fd57135d to your computer and use it in GitHub Desktop.
Using seed for Nest.Js and Prisma Mysql
import { PrismaClient } from '@prisma/client';
export default async function seed(prisma: PrismaClient) {
await prisma.user.createMany({ data: [] });
}
model Seed {
id Int @id @default(autoincrement())
name String
createdAt DateTime @default(now())
}
import { PrismaClient } from '@prisma/client';
import * as fs from 'fs';
import * as path from 'path';
const prisma = new PrismaClient();
async function seed() {
const seedFilesPath = path.join(__dirname + '/seeds');
const seedFiles = await fs
.readdirSync(seedFilesPath)
.filter((file: string) => file.endsWith('.seed.ts'));
for (const seedFile of seedFiles) {
console.log('----------------seed-start------------');
console.log(`Seeding ${seedFile}`);
const seedDatabase = await prisma.seed.findFirst({
where: {
name: seedFile,
},
});
if (seedDatabase) {
console.log(`seed ${seedFile} already exists`);
console.log('----------------seed-end-------------');
continue;
}
await prisma.$transaction(async (prisma) => {
console.log(`Seeding ${seedFile} begin transaction`);
const seedFilePath = path.join(seedFilesPath, seedFile);
// eslint-disable-next-line @typescript-eslint/no-var-requires
const { default: seedFunction } = require(seedFilePath);
await seedFunction(prisma);
await prisma.seed.create({
data: {
name: seedFile,
},
});
console.log(`Seeding ${seedFile} completed`);
});
console.log('----------------seed-end--------------');
}
console.log('All Seeding completed successfully');
}
seed()
.catch((error) => {
console.error('Seeding error:', error);
})
.finally(async () => {
await prisma.$disconnect();
});
@andregaldino
Copy link
Author

andregaldino commented Nov 9, 2023

The seed.tsfile will be located in the prisma/seed.ts directory
The seeds files will be located in the prisma/seeds/*.seed.ts directory

Run seeds

npx prisma db seed

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment