import { randomUUID } from "crypto";
function generateIdempotencyKey(): string {
// UUID v4 is 36 characters and uses only allowed symbols
return randomUUID();
}
async function submitVerification(payload: object) {
const key = generateIdempotencyKey();
// Persist key before calling the API so you can retry after a crash
await db.save({ key, status: "pending", payload });
const res = await fetch("https://masterid.me/api/public/v1/verifications", {
method: "POST",
headers: {
"X-API-Key": process.env.MASTERID_API_KEY!,
"X-API-Secret": process.env.MASTERID_API_SECRET!,
"Content-Type": "application/json",
"Idempotency-Key": key,
},
body: JSON.stringify(payload),
});
const body = await res.json();
if (res.ok) {
await db.update(key, {
status: body.status === 202 ? "processing" : "completed",
sessionId: body.data?.sessionId,
});
}
return { res, body, key };
}
// Retry later using the same key and body
async function retryVerification(key: string) {
const record = await db.find(key);
if (!record) throw new Error("Unknown key");
return submitVerificationWithKey(record.payload, key);
}
async function submitVerificationWithKey(payload: object, key: string) {
const res = await fetch("https://masterid.me/api/public/v1/verifications", {
method: "POST",
headers: {
"X-API-Key": process.env.MASTERID_API_KEY!,
"X-API-Secret": process.env.MASTERID_API_SECRET!,
"Content-Type": "application/json",
"Idempotency-Key": key,
},
body: JSON.stringify(payload),
});
const body = await res.json();
return { res, body, key };
}