Skip to content

Instantly share code, notes, and snippets.

@knezdusan
Last active August 13, 2024 13:56
Show Gist options
  • Save knezdusan/d508657eb52961d71bdaee11a9dbb9f1 to your computer and use it in GitHub Desktop.
Save knezdusan/d508657eb52961d71bdaee11a9dbb9f1 to your computer and use it in GitHub Desktop.
Prisma ORM - seeder function
import { PrismaClient } from '@prisma/client';
import { clients, users, profiles, categories, posts } from './data';
const prisma = new PrismaClient();
async function seeder() {
// Delete all data from the database
await prisma.profile.deleteMany({});
await prisma.post.deleteMany({});
await prisma.category.deleteMany({});
await prisma.user.deleteMany({});
await prisma.client.deleteMany({});
// Upsert clients
await Promise.all(
clients.map(async (client) =>
prisma.client.upsert({
where: { id: client.id },
update: {},
create: client,
})
)
);
// Upsert users
await Promise.all(
users.map(async (user) =>
prisma.user.upsert({
where: { id: user.id },
update: {},
create: user,
})
)
);
// Upsert profiles
await Promise.all(
profiles.map(async (profile) =>
prisma.profile.upsert({
where: { id: profile.id },
update: {},
create: profile,
})
)
);
// Upsert categories
await Promise.all(
categories.map(async (category) =>
prisma.category.upsert({
where: { id: category.id },
update: {},
create: category,
})
)
);
// Upsert posts
await Promise.all(
posts.map(async (post) =>
prisma.post.upsert({
where: { id: post.id },
update: {},
create: post,
})
)
);
}
seeder()
.catch(e => {
console.error(`There was an error while seeding: ${e}`);
process.exit(1);
})
.finally(async () => {
console.log('Successfully seeded database. Closing connection.');
await prisma.$disconnect();
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment