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,6 +85,7 @@ export async function POST() {
} }
return { return {
data: {
date: new Date(row.Date), date: new Date(row.Date),
code: row.Code, code: row.Code,
magnitude: parseFloat(row.Magnitude), magnitude: parseFloat(row.Magnitude),
@ -94,7 +95,8 @@ export async function POST() {
location: row.Location, location: row.Location,
depth: row.Depth, depth: row.Depth,
creatorId: randomCreator.id, creatorId: randomCreator.id,
observatories: { connect: nearbyObservatories }, },
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) {