From a7f19ff45159a998df3c0b4255dcc1c6d189dae7 Mon Sep 17 00:00:00 2001 From: Alexander Daichendt Date: Wed, 1 Jan 2025 23:33:39 +0100 Subject: [PATCH] fix: uid collision handling --- src/pages/admin/api/verifications/index.ts | 29 +++++++++++++++++++++- 1 file changed, 28 insertions(+), 1 deletion(-) diff --git a/src/pages/admin/api/verifications/index.ts b/src/pages/admin/api/verifications/index.ts index 21761dc..fffa951 100644 --- a/src/pages/admin/api/verifications/index.ts +++ b/src/pages/admin/api/verifications/index.ts @@ -2,6 +2,7 @@ import type { APIContext } from "astro"; import { drizzle } from "drizzle-orm/d1"; import { cvTable } from "../../../../db/schema"; import { nanoid } from "nanoid"; +import { eq } from "drizzle-orm"; export const prerender = false; @@ -17,7 +18,33 @@ export async function POST(context: APIContext) { const purpose = formData.get("purpose") as string; const tooling = formData.get("tooling") as string; const created = new Date(); - const uuid = nanoid(8); + + let uuid; + let existing; + let maxAttempts = 10; + + do { + uuid = nanoid(8); + + // check if uuid already exists + existing = await db + .select() + .from(cvTable) + .where(eq(cvTable.uuid, uuid)) + .execute(); + + maxAttempts--; + + // Safety check to prevent infinite loops + if (maxAttempts <= 0) { + return new Response( + JSON.stringify({ + success: false, + error: "Failed to generate unique UUID after multiple attempts", + }), + ); + } + } while (existing.length > 0); try { await db