Switched to single prisma transaction to allow for creation and connection to observatories

This commit is contained in:
Tim Howitz 2025-05-26 14:54:35 +01:00
parent a8fe047019
commit 801b72eb67

View File

@ -47,7 +47,7 @@ export async function POST() {
select: { id: true, latitude: true, longitude: true }, select: { id: true, latitude: true, longitude: true },
}); });
const creators = await prisma.user.findMany({ const creators = await prisma.user.findMany({
where: { role: { in: ["SCIENTIST", "ADMIN"] } }, where: { role: { in: ["SCIENTIST"] } },
}); });
const earthquakes = records.map((row) => { const earthquakes = records.map((row) => {
@ -85,16 +85,18 @@ export async function POST() {
} }
return { return {
date: new Date(row.Date), data: {
code: row.Code, date: new Date(row.Date),
magnitude: parseFloat(row.Magnitude), code: row.Code,
type: row.Type, magnitude: parseFloat(row.Magnitude),
latitude: eqLat, type: row.Type,
longitude: eqLon, latitude: eqLat,
location: row.Location, longitude: eqLon,
depth: row.Depth, location: row.Location,
creatorId: randomCreator.id, depth: row.Depth,
observatories: { connect: nearbyObservatories }, creatorId: randomCreator.id,
},
observatories: nearbyObservatories,
}; };
}); });
@ -102,9 +104,35 @@ export async function POST() {
(earthquake): earthquake is NonNullable<typeof earthquake> => earthquake !== null (earthquake): earthquake is NonNullable<typeof earthquake> => earthquake !== null
); );
// Bulk insert earthquakes with observatory connections // Bulk insert earthquakes and connect observatories in a transaction
await prisma.earthquake.createMany({ await prisma.$transaction(async (tx) => {
data: validEarthquakes, // 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) { if (failedImports.length > 0) {