Make batch transactions actually work

This commit is contained in:
2024-11-20 16:50:38 -05:00
parent 0829e66645
commit c9dcbb3629
3 changed files with 31 additions and 66 deletions

View File

@ -1,33 +1,22 @@
import { jsonError } from "../../../../common.js";
export async function onRequestPost(context: RequestContext) {
const id = context.params.id as string;
const { D1 } = context.env;
await D1.exec("BEGIN TRANSACTION;");
const { event } = context.data;
try {
const row = await D1.prepare(
"UPDATE events SET performed_at = ? WHERE id = ? RETURNING created_by;",
)
.bind(Date.now(), id)
.first();
if (!row) {
await D1.exec("ROLLBACK;");
return jsonError("Event does not exist", 404);
}
await D1.prepare("UPDATE et_members SET points = points + 10 WHERE id = ?;")
.bind(row.created_by)
.run();
await D1.exec("COMMIT;");
await D1.batch([
D1.prepare("UPDATE events SET performed_at = ? WHERE id = ?;").bind(
event.id,
),
D1.prepare(
"UPDATE et_members SET points = points + 10 WHERE id = ?;",
).bind(event.created_by),
]);
} catch (e) {
console.log(e);
await D1.exec("ROLLBACK;");
return jsonError("Failed to update event data", 500);
return jsonError("Failed to complete batch transaction", 500);
}
return new Response(null, {