Skip to content

Commit bf32fd8

Browse files
authored
Merge pull request #813 from nanajelila800-coder/Make-invoice-status-update-atomic
Make invoice status updates atomic
2 parents 22b817a + 8f279c3 commit bf32fd8

1 file changed

Lines changed: 27 additions & 3 deletions

File tree

‎backend/src/invoices/invoices.service.ts‎

Lines changed: 27 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,8 @@
1-
import { BadRequestException, Injectable } from '@nestjs/common';
1+
import {
2+
BadRequestException,
3+
ConflictException,
4+
Injectable,
5+
} from '@nestjs/common';
26
import { GenerateInvoiceProvider } from './providers/generate-invoice.provider';
37
import { FindInvoicesProvider } from './providers/find-invoices.provider';
48
import { PdfInvoiceProvider } from './providers/pdf-invoice.provider';
@@ -69,8 +73,28 @@ export class InvoicesService {
6973

7074
this.statusTransitionProvider.validateTransition(invoice.status, to);
7175

72-
invoice.status = to;
73-
return this.invoicesRepository.save(invoice);
76+
if (invoice.status === to) {
77+
return invoice;
78+
}
79+
80+
const result = await this.invoicesRepository
81+
.createQueryBuilder()
82+
.update(Invoice)
83+
.set({ status: to })
84+
.where('id = :id AND status = :currentStatus', {
85+
id: invoiceId,
86+
currentStatus: invoice.status,
87+
})
88+
.returning('*')
89+
.execute();
90+
91+
if (result.affected !== 1) {
92+
throw new ConflictException(
93+
`Invoice "${invoiceId}" was updated by another request`,
94+
);
95+
}
96+
97+
return this.invoicesRepository.create(result.raw[0]);
7498
}
7599

76100
validateTransition(from: InvoiceStatus, to: InvoiceStatus): void {

0 commit comments

Comments
 (0)