Skip to content

Commit

Permalink
Fixed database seeding script to handle existing users and ensure val…
Browse files Browse the repository at this point in the history
…id foreign key relationships when creating jobs. (#446)
  • Loading branch information
vatan45 authored Oct 5, 2024
1 parent 414e55f commit 904e395
Show file tree
Hide file tree
Showing 3 changed files with 50 additions and 36 deletions.
5 changes: 3 additions & 2 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -9,11 +9,12 @@
"start": "next start",
"lint": "next lint",
"dev:docker": "npm run db:seed & next dev",
"db:seed": "npx prisma db push & npx prisma db seed",
"db:seed": "npx prisma db push && node --import 'data:text/javascript,import { register } from \"node:module\"; import { pathToFileURL } from \"node:url\"; register(\"ts-node/esm\", pathToFileURL(\"./\"));' prisma/seed.ts",
"db:studio": "npx prisma studio",
"check": "prettier --check \"**/*.{ts,tsx,js,jsx,md,mdx,css}\"",
"format": "prettier --write \"**/*.{ts,tsx,js,jsx,md,mdx,css}\"",
"prepare": "husky"
"prepare": "husky",
"db:reset": "npx prisma migrate reset && npm run db:seed"
},
"husky": {
"hooks": {
Expand Down
68 changes: 37 additions & 31 deletions prisma/seed.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,9 @@
/* eslint-disable no-console */
import { Currency, EmployementType, Role, WorkMode } from '@prisma/client';
import { PrismaClient, Currency, EmployementType, Role, WorkMode } from '@prisma/client';
import { faker } from '@faker-js/faker';
import bcrypt from 'bcryptjs';
import prisma from '../src/config/prisma.config';

const prisma = new PrismaClient();

const users = [
{ id: '1', name: 'Jack', email: '[email protected]' },
Expand Down Expand Up @@ -288,36 +289,44 @@ let jobs = [
async function seedUsers() {
try {
const hashedPassword = await bcrypt.hash('123456', 10);
await Promise.all(
users.map(
async (u) =>
await prisma.user.upsert({
where: { id: u.id },
create: {
id: u.id,
email: u.email,
name: u.name,
password: hashedPassword,
role: u.role || Role.USER,
emailVerified: new Date(),
},
update: {},
})
)
);
console.log('✅ user seed successfully');
await prisma.$disconnect();
for (const u of users) {
try {
await prisma.user.upsert({
where: { email: u.email },
update: {},
create: {
id: u.id,
email: u.email,
name: u.name,
password: hashedPassword,
role: u.role || Role.USER,
emailVerified: new Date(),
},
});
console.log(`User created or updated: ${u.email}`);
} catch (error) {
console.log(`Error processing user ${u.email}:`, error);
}
}
console.log('✅ User seed completed');
} catch (error) {
console.log(error);
await prisma.$disconnect();
process.exit(1);
console.error('Error seeding users:', error);
}
}

async function seedJobs() {
try {

const existingUsers = await prisma.user.findMany({
select: { id: true },
});
const existingUserIds = new Set(existingUsers.map(user => user.id));


const validJobs = jobs.filter(job => existingUserIds.has(job.userId));

await Promise.all(
jobs.map(async (j) =>
validJobs.map(async (j) =>
prisma.job.upsert({
where: { id: j.id },
create: {
Expand Down Expand Up @@ -358,12 +367,9 @@ async function seedJobs() {
})
)
);
console.log('✅ job seed successfully');
console.log('✅ Job seed completed successfully');
} catch (error) {
console.error(error);
process.exit(1);
} finally {
await prisma.$disconnect();
console.error('Error seeding jobs:', error);
}
}

Expand All @@ -372,4 +378,4 @@ async function main() {
await seedJobs();
}

main();
main();
13 changes: 10 additions & 3 deletions tsconfig.json
Original file line number Diff line number Diff line change
Expand Up @@ -6,8 +6,8 @@
"strict": true,
"noEmit": true,
"esModuleInterop": true,
"module": "esnext",
"moduleResolution": "bundler",
"module": "ESNext",
"moduleResolution": "node",
"resolveJsonModule": true,
"isolatedModules": true,
"jsx": "preserve",
Expand All @@ -19,7 +19,14 @@
],
"paths": {
"@/*": ["./src/*"]
}
},
"allowSyntheticDefaultImports": true,
"outDir": "./dist",
"target": "ES2020"
},
"ts-node": {
"esm": true,
"experimentalSpecifierResolution": "node"
},
"include": ["next-env.d.ts", "**/*.ts", "**/*.tsx", ".next/types/**/*.ts"],
"exclude": ["node_modules"]
Expand Down

0 comments on commit 904e395

Please sign in to comment.