77 lines
2.0 KiB
JavaScript
77 lines
2.0 KiB
JavaScript
|
|
#!/usr/bin/env node
|
||
|
|
/**
|
||
|
|
* Seed script for micro-learning courses.
|
||
|
|
* Reads prisma/seed-learn.json and creates courses/modules in the database.
|
||
|
|
*
|
||
|
|
* Run:
|
||
|
|
* npx prisma db push
|
||
|
|
* node prisma/seed-learn.js
|
||
|
|
*/
|
||
|
|
|
||
|
|
const { PrismaClient } = require('@prisma/client');
|
||
|
|
const fs = require('fs');
|
||
|
|
const path = require('path');
|
||
|
|
|
||
|
|
const prisma = new PrismaClient();
|
||
|
|
|
||
|
|
async function main() {
|
||
|
|
const seedPath = path.join(__dirname, 'seed-learn.json');
|
||
|
|
const raw = fs.readFileSync(seedPath, 'utf-8');
|
||
|
|
const data = JSON.parse(raw);
|
||
|
|
|
||
|
|
console.log(`Seeding ${data.courses.length} course(s)...`);
|
||
|
|
|
||
|
|
for (const course of data.courses) {
|
||
|
|
const { modules, ...courseData } = course;
|
||
|
|
|
||
|
|
// Upsert course (match by slug)
|
||
|
|
const upserted = await prisma.course.upsert({
|
||
|
|
where: { slug: courseData.slug },
|
||
|
|
update: {
|
||
|
|
title: courseData.title,
|
||
|
|
description: courseData.description,
|
||
|
|
difficulty: courseData.difficulty,
|
||
|
|
imageUrl: courseData.imageUrl,
|
||
|
|
},
|
||
|
|
create: {
|
||
|
|
slug: courseData.slug,
|
||
|
|
title: courseData.title,
|
||
|
|
description: courseData.description,
|
||
|
|
difficulty: courseData.difficulty,
|
||
|
|
imageUrl: courseData.imageUrl,
|
||
|
|
},
|
||
|
|
});
|
||
|
|
|
||
|
|
console.log(` Course: ${upserted.title} (${upserted.id})`);
|
||
|
|
|
||
|
|
// Delete old modules (clean re-seed for dev)
|
||
|
|
await prisma.module.deleteMany({ where: { courseId: upserted.id } });
|
||
|
|
|
||
|
|
// Create modules — strip id/courseId since Prisma auto-generates them
|
||
|
|
if (modules && modules.length > 0) {
|
||
|
|
await prisma.module.createMany({
|
||
|
|
data: modules.map(({ id: _id, courseId: _cid, ...m }) => ({
|
||
|
|
...m,
|
||
|
|
courseId: upserted.id,
|
||
|
|
quizData:
|
||
|
|
typeof m.quizData === 'string'
|
||
|
|
? m.quizData
|
||
|
|
: JSON.stringify(m.quizData || []),
|
||
|
|
})),
|
||
|
|
});
|
||
|
|
console.log(` → ${modules.length} module(s) created`);
|
||
|
|
}
|
||
|
|
}
|
||
|
|
|
||
|
|
console.log('Seeding complete.');
|
||
|
|
}
|
||
|
|
|
||
|
|
main()
|
||
|
|
.catch((e) => {
|
||
|
|
console.error(e);
|
||
|
|
process.exit(1);
|
||
|
|
})
|
||
|
|
.finally(async () => {
|
||
|
|
await prisma.$disconnect();
|
||
|
|
});
|