Switched to single prisma transaction to allow for creation and connection to observatories
This commit is contained in:
parent
a8fe047019
commit
801b72eb67
@ -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,6 +85,7 @@ export async function POST() {
|
||||
}
|
||||
|
||||
return {
|
||||
data: {
|
||||
date: new Date(row.Date),
|
||||
code: row.Code,
|
||||
magnitude: parseFloat(row.Magnitude),
|
||||
@ -94,7 +95,8 @@ export async function POST() {
|
||||
location: row.Location,
|
||||
depth: row.Depth,
|
||||
creatorId: randomCreator.id,
|
||||
observatories: { connect: nearbyObservatories },
|
||||
},
|
||||
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) {
|
||||
|
||||
Loading…
x
Reference in New Issue
Block a user