fix: batch contract database writes
This commit is contained in:
@@ -213,8 +213,8 @@ export const actions: Actions = {
|
||||
|
||||
try {
|
||||
const contractId = crypto.randomUUID();
|
||||
await db.transaction(async (tx) => {
|
||||
await tx.insert(contracts).values({
|
||||
const now = new Date();
|
||||
const createContract = db.insert(contracts).values({
|
||||
id: contractId,
|
||||
organizationId: activeOrganizationId,
|
||||
clientId: form.data.clientId,
|
||||
@@ -224,21 +224,26 @@ export const actions: Actions = {
|
||||
startDate: form.data.startDate,
|
||||
endDate: form.data.endDate,
|
||||
status: 'draft',
|
||||
updatedAt: new Date(),
|
||||
createdAt: new Date()
|
||||
updatedAt: now,
|
||||
createdAt: now
|
||||
});
|
||||
|
||||
const uniqueRoomIds = [...new Set(form.data.roomIds)];
|
||||
if (uniqueRoomIds.length > 0) {
|
||||
await tx.insert(contractRooms).values(
|
||||
await db.batch([
|
||||
createContract,
|
||||
db.insert(contractRooms).values(
|
||||
uniqueRoomIds.map((roomId) => ({
|
||||
contractId,
|
||||
roomId
|
||||
}))
|
||||
);
|
||||
)
|
||||
]);
|
||||
} else {
|
||||
await createContract;
|
||||
}
|
||||
});
|
||||
} catch {
|
||||
} catch (cause) {
|
||||
console.error('Unable to create contract', cause);
|
||||
return message(form, 'Unable to create contract.', { status: 400 });
|
||||
}
|
||||
|
||||
@@ -295,8 +300,8 @@ export const actions: Actions = {
|
||||
}
|
||||
|
||||
try {
|
||||
await db.transaction(async (tx) => {
|
||||
await tx
|
||||
const now = new Date();
|
||||
const updateContract = db
|
||||
.update(contracts)
|
||||
.set({
|
||||
clientId: form.data.clientId,
|
||||
@@ -305,7 +310,7 @@ export const actions: Actions = {
|
||||
depositGbp: form.data.depositGbp,
|
||||
startDate: form.data.startDate,
|
||||
endDate: form.data.endDate,
|
||||
updatedAt: new Date()
|
||||
updatedAt: now
|
||||
})
|
||||
.where(
|
||||
and(
|
||||
@@ -315,19 +320,27 @@ export const actions: Actions = {
|
||||
isNull(contracts.archivedAt)
|
||||
)
|
||||
);
|
||||
|
||||
await tx.delete(contractRooms).where(eq(contractRooms.contractId, form.data.id));
|
||||
const deleteRoomLinks = db
|
||||
.delete(contractRooms)
|
||||
.where(eq(contractRooms.contractId, form.data.id));
|
||||
const uniqueRoomIds = [...new Set(form.data.roomIds)];
|
||||
|
||||
if (uniqueRoomIds.length > 0) {
|
||||
await tx.insert(contractRooms).values(
|
||||
await db.batch([
|
||||
updateContract,
|
||||
deleteRoomLinks,
|
||||
db.insert(contractRooms).values(
|
||||
uniqueRoomIds.map((roomId) => ({
|
||||
contractId: form.data.id,
|
||||
roomId
|
||||
}))
|
||||
);
|
||||
)
|
||||
]);
|
||||
} else {
|
||||
await db.batch([updateContract, deleteRoomLinks]);
|
||||
}
|
||||
});
|
||||
} catch {
|
||||
} catch (cause) {
|
||||
console.error('Unable to update contract', cause);
|
||||
return message(form, 'Unable to update contract.', { status: 400 });
|
||||
}
|
||||
|
||||
|
||||
Reference in New Issue
Block a user