async function criarRegistroPontoIdempotente(dados) {
const idempotencyKey = crypto.randomUUID()
// 1. Persiste intenção localmente
await db.intencao.create({
data: {
idempotencyKey,
operacao: 'criar_registro_ponto',
payload: dados,
status: 'pendente',
},
})
// 2. Envia
try {
const resp = await fetch('https://api.pontua.com.br/registro-ponto', {
method: 'POST',
headers: {
Authorization: `Bearer ${TOKEN}`,
'Content-Type': 'application/json',
},
body: JSON.stringify(dados),
})
if (resp.ok) {
const { id } = await resp.json()
await db.intencao.update({
where: { idempotencyKey },
data: { status: 'sucesso', recursoId: id },
})
return id
}
throw new Error(`HTTP ${resp.status}`)
} catch (err) {
await db.intencao.update({
where: { idempotencyKey },
data: { status: 'erro', erro: String(err) },
})
throw err
}
}
// Antes de retentar, verifique a intenção
async function criarRegistroPontoComRetry(dados) {
const intencaoExistente = await db.intencao.findFirst({
where: { operacao: 'criar_registro_ponto', payload: dados, status: 'sucesso' },
})
if (intencaoExistente) return intencaoExistente.recursoId
return criarRegistroPontoIdempotente(dados)
}