// prisma/seed-menu.ts import { PrismaClient } from '@prisma/mysql/client'; // If you are actually using @prisma/client instead, change to: // import { PrismaClient } from '@prisma/client'; import { MENU_SEEDS, SeedMenu } from './menu-seeds'; const prisma = new PrismaClient(); async function seedMenus() { console.log('Seeding menus...'); // ⚠ Optional: wipe existing menus – ONLY if you are sure there are no FK dependencies // await prisma.menu.deleteMany(); const legacyIdToNewId = new Map(); const inserted = new Set(); // Generic multi-pass insertion: // - Insert records whose parent is either null or already inserted // - Repeat until all are inserted, or no progress (meaning bad parent links) let remaining = MENU_SEEDS.length; while (inserted.size < MENU_SEEDS.length) { let progress = false; for (const seed of MENU_SEEDS) { if (inserted.has(seed.legacyId)) { continue; } // If has a parent, but parent not inserted yet → skip this round if ( seed.legacyParentId !== null && !legacyIdToNewId.has(seed.legacyParentId) ) { continue; } const parentId = seed.legacyParentId === null ? null : legacyIdToNewId.get(seed.legacyParentId)!; const created = await prisma.menu.create({ data: { parentId, title: seed.title, status: true, // from original dump (1 = true) type: seed.type, order: seed.order, frontendAuth: null, // or derive something if you decide later path: seed.path, name: seed.name, icon: seed.icon, redirect: null, // can be filled per menu if needed component_key: null, // your Prisma field is `component_key` meta: seed.meta ?? undefined, // default action flags; adjust if needed canView: 0, canCreate: 0, canUpdate: 0, canDelete: 0, // createTime / updateTime are handled by defaults / @updatedAt }, }); legacyIdToNewId.set(seed.legacyId, created.id); inserted.add(seed.legacyId); remaining -= 1; progress = true; console.log( `Inserted menu [legacyId=${seed.legacyId}, newId=${created.id}, name=${seed.name}]`, ); } if (!progress) { // Nothing could be inserted in this pass -> some parentId is invalid or cyclic const pending = MENU_SEEDS.filter((s) => !inserted.has(s.legacyId)).map( (s) => ({ legacyId: s.legacyId, legacyParentId: s.legacyParentId, }), ); console.error( 'Could not resolve parents for the following menus:', pending, ); throw new Error( 'Menu seeding aborted: unresolved parent relationships. Check legacyParentId values.', ); } } console.log('Menu seeding completed successfully.'); } async function main() { try { await seedMenus(); } catch (err) { console.error('Error during menu seeding:', err); process.exitCode = 1; } finally { await prisma.$disconnect(); } } void main();