Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

184
Visualizações
Cloud Functions: Realtime Database transaction not working with condition

I am trying to decrease the field amount which represents the amount of products available for sale.

My database is structured like below:

- Stock
 - StoreId
  - DepartmentId
   - ProductId
    + price
    + amount

My storeId has a fixed value and I am only looping through the variables DepartmentId and ProductId.

Below is how I created a node array or children array for the transaction:

  const childArray = [];
  depIds.forEach(depId => {
    const prodIds = groupedProducts[depId].reduce((acc, val) => [...acc, val.prodId], []);
    prodIds.forEach(prodId => {

      childArray.push(admin.database().ref("Stock")
        .child(storeId)
        .child(depId)
        .child(prodId)
        .child("amount")
        .once('value'));
    });
  });

When I add the condition: amount > 0, nothing happens. It only works when I remove the condition.

const snapshots = await Promise.all(childArray);
snapshots.forEach(snapshot => {
  snapshot.ref.transaction(amount => {
    //if (amount) return amount + admin.database.ServerValue.increment(-1);
    if (amount > 0) return amount - 1;
        
  })
})

Furthermore, what I really need is to compare the amount in the database with the amount coming from the request (let's call it qty)

For this, I would have to retrieve the current path for productId and departmentId. But as showed below, snapshot.ref.parent does not return the path.

snapshots.forEach(snapshot => {
  snapshot.ref.transaction(amount => {
    //if (amount > 0 & amount >= qty) return amount + admin.database.ServerValue.increment(-qty);

    const productPath = snapshot.ref.parent;
    const departmentPath = snapshot.ref.parent.parent;
    // Get qty based on productPath and departmentPath
    if (amount > 0 & amount >= qty) return amount - qty;
        
  })
})

So, I have three questions:

  1. How to retrieve the current paths for departmentId and productId
  2. How to update the field amount based on a condition and abort the whole transaction if any condition is not satisfied
  3. How to make admin.database.ServerValue.increment(-qty) work

I appreciate any help!

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

You don't need a transaction for this. Instead, once you know the full path of the node(s) to update, you can use increment() and then use security rules to validate that the value doesn't go below 0.

So in code that'd be:

admin.database().ref("Stock")
  .child(storeId)
  .child(depId)
  .child(prodId)
  .update({ "amount", admin.database.ServerValue.increment(-1));

And then in the rules:

{
  "rules": {
    "Stock": {
      "$storeId": {
        "$depId": {
          "$prodId": {
            "amount": {
              ".validate": "newData.val() >= 0"
            }
          }
        }
      }
    }
  }
}
about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda