JavaScript Transactions with API calls [closed]

I currently have a list of objects like this:

{
   "json": [
        {
           "sub-objectA": {(data in here)},
           "sub-objectB": {(data in here)},
           "sub-objectC": {(data in here)}
        },
        ...
   ]
}

Each of the sub-object in the object has its own controller, which contains a POST method that will add that object to a table in the database (For example POST for sub-objectA will be add to SubObjATable).

What I am doing here is I want to transfer this list of object from one database to another by using a for-loop in the frontend, with something like this:

json.forEach(object => {
   //Adding each sub-object to the destination database in here  
   //with each sub-object POST API call
})

But now I want to move one more step is that rather than just using a for loop and transfer each sub-object separately, I want to transfer them in a transaction as a whole. For example:

  • Insertion of sub-objectA (success)
  • Insertion of sub-objectB (success)
  • Insertion of sub-objectC (success)
    => Commit changes to database
  • If one of the methods above fails => Rollback any changes to the database

My question is that is it possible to do this type of transaction in the frontend with the use of API calls instead of using db.connection from JavaScript (since I can access the database through a JWT token, which will be used in the API calls). I have done some research but I only see the db.connection method. Thank you very much for the help.

I am using .Net Core WebAPI for backend and VueJS for frontend.

  • 1

    Yes, that seems possible. Have you attempted something yet, and have you encountered a problem?

    – 

  • So far I have the lists and the API calls to get the list of objects, what I am stuck at is how to make those calls in the transaction as a whole since each of the object A, B and C has separate POST method to add into the database

    – 

  • What happens if you don’t make the call for C, either due to a software bug or a malicious user? Your transaction is going to be left open forever and lock your database. Having each object be their own call is fine and all, but tying them together with a single transaction is strange.

    – 

  • I really think that sharing a database transaction over multiple threads is a really bad idea, if not impossible. When do you want to commit the transaction? What’s really the benefit of sending each object to the API server one at a time and using the DB’s memory to create a transaction rather than sending one payload to the API server and letting it deal with the transaction in a single thread?

    – 

  • So you mean that it would be better to have a transaction that handle the transferring of the whole object in a single thread rather than having a transaction with multiple threads right?

    – 

Leave a Comment