const { Sequelize, DataTypes } = require('sequelize');
// Initialize Sequelize instance
const sequelize = new Sequelize('database', 'username', 'password', {
host: 'localhost',
dialect: 'mysql',
});
// Define a model for the database table
const User = sequelize.define('User', {
username: {
type: DataTypes.STRING,
allowNull: false,
},
email: {
type: DataTypes.STRING,
allowNull: false,
},
});
// Define a transaction to perform multiple operations atomically
const transaction = await sequelize.transaction();
try {
// Create a new user within the transaction
const newUser = await User.create({ username: 'JohnDoe', email: '[email protected]' }, { transaction });
// Update the user's email within the transaction
await newUser.update({ email: '[email protected]' }, { transaction });
// Commit the transaction if all operations succeed
await transaction.commit();
} catch (error) {
// Rollback the transaction if any operation fails
await transaction.rollback();
}
// Close the Sequelize connection
await sequelize.close();