'Handle multiple request in Node.js
How to handle multiple request at the same time? I couldn't find anything related to Nestjs and prisma. Does anybody has any recommended article or so?
To provide simple example - let's say I am building e-commerce API. I have simplified orderService in Nestjs. Business logic says, that user can not apply more than 1 voucher in an order. Let's say user somehow sends from UI two separate request at the same time. Condition order.vouchers.length > 1 is true for both requests which results accepting and updating both vouchers.
@Injectable('')
export class OrderService {
constructor(private readonly database: DatabaseService) {}
async applyVoucher(voucherDto: voucherDto) {
const order = await this.database.orders.findOne({where: {id: voucherDto.orderId}})
if (order.vouchers.length > 1) {
return new HttpException('Can not add more than 2 voucher', 400);
}
await someHeavyWorkFunction()
await this.database.orders.update({ where:{ id: voucherDto.orderId}, data: { vouchers: [...order.vouchers, voucherDto.voucher]}})
}
If I call my API endpoint which resolves calling this service three times in a row in a same time, expected behaviour is that 2 requests successfully pass and last request fails. However, this is not the case and all 3 requests pass ending up with 3 vouchers in database.
Solution 1:[1]
You can work with transactions, please follow this tutorial
A database transaction symbolizes a unit of work performed within a database management system (or similar system) against a database and treated in a coherent and reliable way independent of other transactions. A transaction generally represents any change in a database. Transactions in a database environment have two main purposes:
If you want to use an ORM like Typeorm for your projects, you can use this tutorial
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Mohammad Yaser Ahmadi |
