My backend app is being built using Express, Typescript, Typeorm, and Postgres.
Let's consider a table named Restaurant
with columns:
restaurant_id
order (Integer)
quota (Integer)
The aim is to set an upper limit on the number of orders a restaurant can receive. When multiple clients place orders, the order
value should increment by one each time.
For instance, if a restaurant has:
id: 1
order : 9
quota : 10
and two clients try to place orders simultaneously, there could be a conflict.
I want the system to prioritize the first request and increment the order
value by one, resulting in:
id: 1
order : 10
quota : 10
The second client's request would fail to increment the value and receive an error message indicating that the quota has been reached.
A couple of considerations:
In Typeorm / Postgres, is it possible to set a maximum value for an integer column? This way, if the value exceeds the limit, an error will be triggered?
I am contemplating restricting the endpoint responsible for incrementing the order to allow only one call at a time. Even if the aforementioned feature is implemented, I still want to prevent concurrent execution of the endpoint under other circumstances.
(This is not functional code, purely for reference):
app.put('/restaurant_order/:restaurantId', async (req, res) => {
const instance = await Restaurant.findOne(restaurantId);
if (instance.order < instance.quota){
await getConnection()
.createQueryBuilder()
.update(Restaurant)
.set({ order: () => `order + 1` })
.where("id = :id", { id: restaurantId })
.execute();
}
res.respond({
...
})
});
The main question here is:
How can I enforce this limit in Express? Is it possible to configure Express so that the
app.put('/restaurant_order/:restaurantId', ...)
route prevents parallel calls and allows only one call at a time per restaurantId
?