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 },
});
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<typeof earthquake> => 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) {