簡體   English   中英

Node.js - 如何使用 Sequelize 交易

[英]Node.js - How to use Sequelize transaction

我是sequelize的初學者,無法進行交易。 文檔不清楚,使以下示例無法適應我的要求。

  return sequelize.transaction(t => {
  // chain all your queries here. make sure you return them.
  return User.create({
    firstName: 'Abraham',
    lastName: 'Lincoln'
  }, {transaction: t}).then(user => {
    return user.setShooter({
      firstName: 'John',
      lastName: 'Boothe'
    }, {transaction: t});
  });

}).then(result => {
  // Transaction has been committed
  // result is whatever the result of the promise chain returned to the transaction callback
}).catch(err => {
  // Transaction has been rolled back
  // err is whatever rejected the promise chain returned to the transaction callback
});

首先,我必須在“Conto”中插入一個元組,然后在“Preferenze”中插入另一個元組,最后根據“tipo”屬性在“ContoPersonale”或“ContoAziendale”中插入一個元組。

如果這些查詢中只有一個失敗,則事務必須進行總回滾,提交。

查詢是:

Conto.create({
        id: nextId(),
        mail: reg.email,
        password: reg.password,
        tipo: reg.tipo,
        telefono: reg.telefono,
        idTelegram: reg.telegram,
        saldo: saldoIniziale,
        iban: generaIBAN()
    })

Preferenze.create({
        refConto: 68541
    })

if (tipo == 0) {
        ContoPersonale.create({
        nomeint: reg.nome,
        cognomeint: reg.cognome,
        dataN: reg.datan,
        cf: reg.cf,
        refConto: nextId()
        }) 
        }
else if (tipo == 1) { 
        ContoAziendale.create({
        pIva: reg.piva,
        ragioneSociale: reg.ragsoc,
        refConto: nextId()
        })
        }

對於事務,您將其傳遞給您希望成為事務一部分的每個查詢,然后在完成時調用transaction.commit()transaction.rollback()以回滾所有更改。 這可以使用thenables來完成,但是使用async/await時會更清楚。

由於您的查詢都不相互依賴,因此您也可以使用Promise.all()同時進行查詢。

thenables (自動提交)

sequelize.transaction((transaction) => {
  // execute all queries, pass in transaction
  return Promise.all([
    Conto.create({
      id: nextId(),
      mail: reg.email,
      password: reg.password,
      tipo: reg.tipo,
      telefono: reg.telefono,
      idTelegram: reg.telegram,
      saldo: saldoIniziale,
      iban: generaIBAN()
    }, { transaction }),

    Preferenze.create({
      refConto: 68541
    }, { transaction }),

    // this query is determined by "tipo"
    tipo === 0
      ? ContoPersonale.create({
          nomeint: reg.nome,
          cognomeint: reg.cognome,
          dataN: reg.datan,
          cf: reg.cf,
          refConto: nextId()
        }, { transaction })
      : ContoAziendale.create({
          pIva: reg.piva,
          ragioneSociale: reg.ragsoc,
          refConto: nextId()
        }, { transaction })
  ]);

  // if we get here it will auto commit
  // if there is an error it with automatically roll back.

})
.then(() => {
  console.log('queries ran successfully');
})
.catch((err) => {
  console.log('queries failed', err);
});

異步/等待

let transaction;
try {
  // start a new transaction
  transaction = await sequelize.transaction();

  // run queries, pass in transaction
  await Promise.all([
    Conto.create({
      id: nextId(),
      mail: reg.email,
      password: reg.password,
      tipo: reg.tipo,
      telefono: reg.telefono,
      idTelegram: reg.telegram,
      saldo: saldoIniziale,
      iban: generaIBAN()
    }, { transaction }),

    Preferenze.create({
      refConto: 68541
    }, { transaction }),

    // this query is determined by "tipo"
    tipo === 0
      ? ContoPersonale.create({
          nomeint: reg.nome,
          cognomeint: reg.cognome,
          dataN: reg.datan,
          cf: reg.cf,
          refConto: nextId()
        }, { transaction })
      : ContoAziendale.create({
          pIva: reg.piva,
          ragioneSociale: reg.ragsoc,
          refConto: nextId()
        }, { transaction })
  ]);

  // if we get here they ran successfully, so...
  await transaction.commit();
} catch (err) {
  // if we got an error and we created the transaction, roll it back
  if (transaction) {
    await transaction.rollback();
  }
  console.log('Err', err);
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM