diff --git a/src/app/api/import-earthquakes/route.ts b/src/app/api/import-earthquakes/route.ts index e43a09e..17091ec 100644 --- a/src/app/api/import-earthquakes/route.ts +++ b/src/app/api/import-earthquakes/route.ts @@ -47,7 +47,7 @@ export async function POST() { select: { id: true, latitude: true, longitude: true }, }); const creators = await prisma.user.findMany({ - where: { role: { in: ["SCIENTIST", "ADMIN"] } }, + where: { role: { in: ["SCIENTIST"] } }, }); const earthquakes = records.map((row) => { @@ -85,16 +85,18 @@ export async function POST() { } return { - date: new Date(row.Date), - code: row.Code, - magnitude: parseFloat(row.Magnitude), - type: row.Type, - latitude: eqLat, - longitude: eqLon, - location: row.Location, - depth: row.Depth, - creatorId: randomCreator.id, - observatories: { connect: nearbyObservatories }, + data: { + date: new Date(row.Date), + code: row.Code, + magnitude: parseFloat(row.Magnitude), + type: row.Type, + latitude: eqLat, + longitude: eqLon, + location: row.Location, + depth: row.Depth, + creatorId: randomCreator.id, + }, + observatories: nearbyObservatories, }; }); @@ -102,9 +104,35 @@ export async function POST() { (earthquake): earthquake is NonNullable => earthquake !== null ); - // Bulk insert earthquakes with observatory connections - await prisma.earthquake.createMany({ - data: validEarthquakes, + // Bulk insert earthquakes and connect observatories in a transaction + await prisma.$transaction(async (tx) => { + // Insert earthquakes + await tx.earthquake.createMany({ + data: validEarthquakes.map((eq) => eq.data), + }); + + // Fetch created earthquakes by their unique codes + const createdEarthquakes = await tx.earthquake.findMany({ + where: { + code: { in: validEarthquakes.map((eq) => eq.data.code) }, + }, + select: { id: true, code: true }, + }); + + // Connect observatories to each earthquake + await Promise.all( + validEarthquakes.map(async (eq) => { + const createdEq = createdEarthquakes.find((ce) => ce.code === eq.data.code); + if (createdEq && eq.observatories.length > 0) { + await tx.earthquake.update({ + where: { id: createdEq.id }, + data: { + observatories: { connect: eq.observatories }, + }, + }); + } + }) + ); }); if (failedImports.length > 0) {