fix(web): wanted POST converges on P2002 unique race instead of 500

Two concurrent Wants for the same release-group both pass the
findUnique existence check as absent; the loser's create() then hits
the rgMbid unique constraint and threw an uncaught P2002, 500ing the
request. Wrap the create in try/catch and fall back to the same
update-and-return-200 path on P2002, converging instead of erroring.
Non-P2002 errors are rethrown unchanged.
This commit is contained in:
Jonathan
2026-07-13 00:40:29 +02:00
parent 9c793f42d1
commit 44c1b1a62a
2 changed files with 55 additions and 13 deletions
+26 -13
View File
@@ -1,3 +1,4 @@
import { Prisma } from "@prisma/client";
import { prisma } from "@/lib/db";
import { searchReleaseGroup } from "@/lib/musicbrainz";
@@ -49,17 +50,29 @@ export async function POST(request: Request) {
const updated = await prisma.monitoredRelease.update({ where: { rgMbid: match.rgMbid }, data: { monitored: true } });
return Response.json({ id: updated.id, album: updated.album, monitored: updated.monitored }, { status: 200 });
}
const created = await prisma.monitoredRelease.create({
data: {
artistMbid: match.artistMbid,
artistName: match.artistName,
rgMbid: match.rgMbid,
album: match.title,
primaryType: match.primaryType,
secondaryTypes: match.secondaryTypes,
firstReleaseDate: match.firstReleaseDate,
monitored: true,
},
});
return Response.json({ id: created.id, album: created.album, monitored: created.monitored }, { status: 201 });
try {
const created = await prisma.monitoredRelease.create({
data: {
artistMbid: match.artistMbid,
artistName: match.artistName,
rgMbid: match.rgMbid,
album: match.title,
primaryType: match.primaryType,
secondaryTypes: match.secondaryTypes,
firstReleaseDate: match.firstReleaseDate,
monitored: true,
},
});
return Response.json({ id: created.id, album: created.album, monitored: created.monitored }, { status: 201 });
} catch (e) {
if (e instanceof Prisma.PrismaClientKnownRequestError && e.code === "P2002") {
// Concurrent Want for the same release-group won the create; converge to the update path.
const updated = await prisma.monitoredRelease.update({
where: { rgMbid: match.rgMbid },
data: { monitored: true },
});
return Response.json({ id: updated.id, album: updated.album, monitored: updated.monitored }, { status: 200 });
}
throw e;
}
}