Maintaining database consistency for multiple clients making simultaneous requests in Postgres with Typeorm and Express

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:

  1. 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?

  2. 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?

Answer №1

Before proceeding, it is important to review the relevant section of the documentation: https://www.postgresql.org/docs/8.3/ddl-constraints.html

For instance:

CREATE TABLE products (
    product_no integer,
    name text,
    price numeric CHECK (price > 0)
);

In this scenario, it can be implemented as follows:

order integer CHECK (order < quota)

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

"Production environment encounters issues with react helper imports, whereas development environment has no trouble with

I have a JavaScript file named "globalHelper.js" which looks like this: exports.myMethod = (data) => { // method implementation here } exports.myOtherMethod = () => { ... } and so forth... When I want to use my Helper in other files, I import it ...

How can I show the post JSON response that was retrieved in ReactJS on the same form component that was used to submit the value?

Thank you for your assistance in advance. I am currently developing a web crawler that will operate in the following steps: The user inputs the seed URL (front-end) The user clicks the submit button (front-end) The seed URL is processed by the backend usi ...

Accessing the session object within an Express middleware function is crucial for

This is my unique Express middleware setup: var app = express() .use(express.cookieParser()) .use(express.session({secret: 'HiddenSecret'})) .use(express.bodyParser()) .use(function displaySession(req, res, next) { consol ...

Unexpected behavior observed with callback function when inserting a query in Node.js

Having a minor issue with using the POST method and adding an INSERT. The functionality works correctly as shown below, but I am looking to implement a callback after the data has been inserted. Currently, the database is updated successfully, but I am una ...

Issues arise when attempting to store data into an array with the assistance of FileReader

I am currently working on an Angular4 project where I am facing an issue with saving Blob data returned from my API call to an array of pictures in base64 format. This is so that I can later display the images using *ngFor. Here is the API call I am makin ...

Is it possible to configure a unique Bearer Access Token in the "angular-oauth2-oidc" library?

For my Facebook login, I have set up a custom endpoint where the client sends the Facebook access token. In my Ionic App, I use the '@ionic-native/facebook/ngx' package to retrieve this token. Within a Laravel Json API controller, I utilize Soci ...

Tips for adding a "Select All" feature to a dropdown list?

Currently, I have a dropdown list with a filter for IN and OUT values. The functionality is working as expected: <select class="form-select" style="max-width: 100px" [ngModel]="selectedBrand" (ngModelChange)="onChangeT ...

How can I align the Socket.io path on the client with the directory structure of my Node.js server?

Currently, I am utilizing socket.io with node.js along with Expressjs. As I serve my HTML page, I have the socket.io.js file linked directly in a script tag: <script src="/socket.io/socket.io.js"></script> I'm facing some difficulty match ...

Passing an array from a parent component to a child component in Angular

Just to give you some background, I only started my Angular learning journey about a week ago, so feel free to start from the very beginning. So, how can this be achieved? Inside app.component.ts, there is a standard array that needs to be accessible by m ...

Utilizing a variable to pass props to a component (instead of a static component) within React Router 5

In react-router 5, you can pass props to a child component in this way: <Route path="/" exact render={ props => <MyPage title={myTitle} dataPath={myDataPath} {...props} />} /> However, I am using a route model in my ...

The getMonthlyBalances function is providing inaccurate results when calculating stock balances

One of my functions is called getMonthlyBalances, which takes in two arrays - stocks and trades. It calculates the monthly balance of a user's stock holdings based on their trade history. The stocks array includes objects with stock ID, prices, and da ...

Encountering Errors while executing the yarn build or tsc commands

Whenever I attempt to build a project or run the yarn tsc command, I encounter various types of errors. This seems to be due to them being installed in the incorrect location. But what could be causing this issue? Feel free to ask for more details if nee ...

Traversing through JSON objects in Angular 2

I am currently facing an issue while trying to iterate through a JSON object. Below is the sample JSON data: floors.ts this.floors= [ { floorName: "floor 1", result: [ { resFloor: "1", ...

What is the process of attaching a property to every object within an array using TypeScript?

In my search for adding a property to each object in an array, I came across a solution in AngularJs on Stack Overflow. However, I attempted the following approach which did not yield the desired outcome. Any assistance would be greatly appreciated. ex ...

Received an error while using an Express router: "Unable to access property 'caseSensitive' of undefined."

javaScriptCode app.js const express = require('express') const app = express() const {route} = require('./routes/route') app.use(express.static('./public')); app.use(express.json()); app.use(express.urlencoded()); app.use(rout ...

Email Form Application: Utilizing NodeJs and Express - Error: URL Not Found /

I'm encountering a "cannot GET" error whenever I try to run my application on a live server using VS Code. My assumption is that the issue lies within my routing configuration, but I'm struggling to identify the exact problem. Any assistance woul ...

Obtaining undefined values for req and resolvedUrl in GetServerSideProps function

In my project, I am currently using next.js version ""next": "^12.1.4"" and node version ""@types/node": "^14.14.6". I have created a function called getServerSideProps with parameters req and resolvedUrl. When the ...

Total the values of several items within the array

Here is the data I currently have: const arrayA = [{name:'a', amount: 10, serviceId: '23a', test:'SUCCESS'}, {name:'a', amount: 9, test:'FAIL'}, {name:'b', amount: ...

Using Angular's ElementRef to set focus on an ion-textarea: "The 'setFocus' property is not found on the 'ElementRef' type."

After developing a textarea component that automatically focuses itself when created using the ngAfterViewInit() method, everything seemed to be working perfectly as expected. ngAfterViewInit() { if(this.text.length===0){ this.theinput.setFocus(); ...

Generating a Radio Button Label on-the-fly using Angular 8 with Typescript, HTML, and SCSS

Struggling with generating a radio button name dynamically? Looking to learn how to dynamically generate a radio button name in your HTML code? Check out the snippet below: <table> <td> <input type="radio" #radio [id]="inputId" ...