async function incrementScore(projectUrl: string, path: string, token: string) {
const url = `${projectUrl}/${path}.json?auth=${token}`;
while (true) {
// 1. Read with ETag
const readResponse = await fetch(url, {
headers: { 'X-Firebase-ETag': 'true' }
});
const etag = readResponse.headers.get('ETag');
const currentValue = await readResponse.json();
// 2. Compute new value
const newValue = (currentValue ?? 0) + 1;
// 3. Conditional write
const writeResponse = await fetch(url, {
method: 'PUT',
headers: { 'If-Match': etag! },
body: JSON.stringify(newValue)
});
if (writeResponse.ok) {
return newValue; // Success
}
if (writeResponse.status === 412) {
continue; // Conflict — retry with fresh data
}
throw new Error(`Unexpected status: ${writeResponse.status}`);
}
}