Handle one item at a time in the API

Asked

Viewed 43 times

0

I have a API that makes the POST of Item in the database, but before doing the POST she makes a GET to obtain a code for the Item that will be saved.

NOTE: this code cannot be repeated in the database, it has to be unique.

When sending an array with two items, they are taking the same code, giving conflict when writing to DB.

Imagery: POST being threshed. inserir a descrição da imagem aqui

The two items pass on line 102, and then the two items pass on line 113.

How to make one item at a time get the code and then save to the bank so the next items do the same process?

  • Have you ever tried to make a foreach when you have more than 01 item ? So you will record one item at a time and get a new code for the item at each iteration.

  • I already have a FOR in the application that sends item by item to the API.

  • put the code of that part there. :)

  • for (var i = 0; i < $rootScope.itemObj.length; i++) {&#xA; Prevendas.incluirItemPreVenda($rootScope.itemObj[i]).success(function () {&#xA; console.log("incluirItemPreVenda OK");&#xA; }).error(function () {&#xA; console.log("incluirItemPreVenda Erro");&#xA; })&#xA;}

  • This is happening because you are making several asynchronous calls, which database are you using? There is no possibility to put this field as identitiy/autoincrement?

  • Which database you use?

  • dbc database, but I can’t use autoincrement because I can’t change the database because it’s used by another desktop system.

Show 2 more comments

1 answer

1


The solution was to control the sending of items to the API by sending one item at a time, because the API has no control over how many items are being saved. Follows code that makes the POST in the API and sends item only when the previous one has been saved.

//  Faz a inclusão do objeto de itemObj no banco de dados.
function incluirItensFunc(tnNrItem) {
    //  Atribui o cdprevenda ao itemObj[].
    $rootScope.itemObj[tnNrItem].Cdprevenda = $rootScope.prevendaSelecionado;
    if (tnNrItem == ($rootScope.itemObj.length - 1)) {
        Prevendas.incluirItemPreVenda($rootScope.itemObj[tnNrItem]).success(function () {
            console.log("incluirItemPreVenda OK");
            $rootScope.itemObj = [];
            calcularTotalPreVendaFunc();
        }).error(function () {
            console.log("incluirItemPreVenda Erro");
        })
    }
    else {
        Prevendas.incluirItemPreVenda($rootScope.itemObj[tnNrItem]).success(function () {
            console.log("incluirItemPreVenda OK");
            //  Chama a função incluirItensFunc novamente passando tnNrItem + 1 como parâmetro.
            incluirItensFunc(tnNrItem + 1);
        }).error(function () {
            console.log("incluirItemPreVenda Erro");
        })
    }
}

Browser other questions tagged

You are not signed in. Login or sign up in order to post.