Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Good practice to deal with POST api and loss of internet connection

I own an hybrid application, whose main language is Javascript (AngularJs) so.
Basically, I have a form aiming to create an object through my REST api (on a distinct server).

My save function is conceptually like this:

$scope.save = function () {
  var promise = CRUDService.post($scope.myElementToPost);
  promise.then(function (response) {
      //when 20X status
  }, function () {
      //when 40X - 50X status
  });            
};

Let's suppose the triggering of the save function, and really immediately after the POST request, the mobile loses internet connection, leading to an error at client side, therefore involving the error callback.

In this "exceptional" case, the element would be well created on server's database, but the javascript success callback would not be triggered, since a loss of internet connection leads to an "error".

How to deal with this case?
How to avoid user to re-submit the form (he would be ignorant of the first creation of the element on the server side)?

like image 484
Mik378 Avatar asked Oct 31 '22 09:10

Mik378


1 Answers

You may create a transaction model:

  1. Client creates a unique transaction ID for this request and attach to the Rest call

  2. Server receives the request, check the transaction log for previous calls with the same id.

  3. if it is a new transaction, server stores this transaction ID in a log with a status 'pending'. Server then processes the request. Server updates the transaction log status to 'processed'. Server then sends the response to the client and stores response in the transaction log

  4. If it is an old transaction, server resend response to client

  5. Client receives response, client sends transaction completed signal to the server.

  6. Server removes/updates transaction log to 'finished'

Failure in the 5th step, the client can resend the request with the same transaction id, without the risk of duplicate records

like image 166
kabapy Avatar answered Nov 09 '22 07:11

kabapy