How to create a sequelize transaction

Hey guys,

I updated models/index.js file to store sequelize object as bellow so I can use sequelize.transaction() & then rollback my transactions if an error occurred during the process :

const fs = require('fs');
const path = require('path');
const Sequelize = require('sequelize');

const databasesConfiguration = require('../config/databases');

const connections = {};
const db = {};
let sequelize = null;

databasesConfiguration.forEach((databaseInfo) => {
  const connection = new Sequelize(databaseInfo.connection.url, databaseInfo.connection.options);
  connections[databaseInfo.name] = connection;
  sequelize = connection;

  const modelsDir = databaseInfo.modelsDir || path.join(__dirname, databaseInfo.name);
  fs
    .readdirSync(modelsDir)
    .filter((file) => file.indexOf('.') !== 0 && file !== 'index.js')
    .forEach((file) => {
      try {
        const model = connection.import(path.join(modelsDir, file));
        db[model.name] = model;
      } catch (error) {
        console.error(`Model creation error: ${error}`);
      }
    });
});

Object.keys(db).forEach((modelName) => {
  if ('associate' in db[modelName]) {
    db[modelName].associate(db);
  }
});

db.objectMapping = Sequelize;
db.connections = connections;
db.sequelize = sequelize;

module.exports = db;

I created a sequelize transaction before a succession of update (multiple models), & noticed that the rollback doesn’t work.

Here is an example of how I am using it.

          try {
            // check compliance 
            await refundRequestController.checkRefundRequestCompliance(id, attrs['Smthg'], refundRequest);
            // update number 1 
            await myCovers.update({ refunded: amount }, { where: { id } }, { transaction });
            // update number 2
            await myCovers.update({ refunded: amount }, { where: { id2 } }, { transaction });
            await transaction.commit();
          }
          catch (error) {
            await transaction.rollback();
            return res.status(400).send({ error });
          }

Any idea ?

Thanks in avance for your help.

“forest-express-sequelize”: “^7.0.0”,
“sequelize”: “~5.15.1”,

Hello @nadiab,

I’d like to know if possible how do you create your transaction variable.
Usually, you do not need to modify the models/index.js.

You can directly access to the sequelize object from your model.
For example, if your model is named myCovers , you can create:

const transaction = await myCovers.sequelize.transaction()

Let me know if it helps :slight_smile:

Hello @Guillaume_Cisco

Thanks for reaching out.
I set transaction this way :

const transaction = await db.sequelize.transaction();

I tried your way & have the same result :confused:
If my update number 2 failed the update number 1 isn’t rolled back. It’s like transaction doesn’t work.
How did you use it in forestadmin projects please ?

Thanks in advance for your help

According to the Sequelize documentation, it looks like the where clause and the transaction should be in the same object.

Could you replace:

await myCovers.update({ refunded: amount }, { where: { id } }, { transaction });
// update number 2
await myCovers.update({ refunded: amount }, { where: { id2 } }, { transaction });

by

await myCovers.update({ refunded: amount }, { where: { id }, transaction });
// update number 2
await myCovers.update({ refunded: amount }, { where: { id2 }, transaction });

Tell me if it helps :slight_smile:

Hello @Guillaume_Cisco

Oh my bad, well spotted !
It works thank you

Have a nice day

1 Like