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”,