arve
arve

Reputation: 801

how to use transactions in sequelize?

I have written two classes and migrations files for MySQL database using sequelize. how can I save the user and his children using transactions in node.js? I want to create, a class where I can encapsulate all the database communications in one file and then call it from my CRUD methods.

user class :

'use strict';
module.exports = function(sequelize, DataTypes) {
  const User = sequelize.define('User', {
    id : {
        type: DataTypes.INTEGER(11),
        allowNull: false, 
        autoIncrement:true,
        primaryKey:true
    },
    firstName : {
        type: DataTypes.STRING(50),
        allowNull: false
    },
    lastName : {
        type: DataTypes.STRING(50),
        allowNull: false
    },
    dateOfBirth : {
        type: DataTypes.DATE,
        allowNull: false
    }
  });

  return User;
};

children class :

'use strict';
module.exports = function(sequelize, DataTypes) {
  const Children= sequelize.define('Children', {
    id : {
        type: DataTypes.INTEGER(11),
        allowNull: false, 
        autoIncrement:true,
        primaryKey:true
    },
    userId : {
        type: DataTypes.INTEGER(11),
        allowNull: true,
        references : {
            model : 'Users',
            key:'id'
        }
    },
    status : {
        type: DataTypes.BOOLEAN,
        allowNull: false,
        defaulValue: false
    },
    firstName : {
        type: DataTypes.STRING(50),
        allowNull: false
    },
    lastName : {
        type: DataTypes.STRING(50),
        allowNull: false
    },
    dateOfBirth : {
        type: DataTypes.DATE,
        allowNull: false
    }
  });
  return Children;
};

Upvotes: 0

Views: 2133

Answers (1)

Nilanka Manoj
Nilanka Manoj

Reputation: 3738

Try :

let transaction;    
try {
    // get transaction
    transaction = await sequelize.transaction();

    //save here
    User.build({
        firstName: "John"
        //other attributes
    }).save().then(newUser => {
        const id = newUser.id;
        Children.build({
                firstNames: "fsf"
                userId: id // from newly created user
                //other attributes
            })
            .save()
            .then(children => console.log("svaed"))
    }).catch(function(error) {
        // error
    });

    // commit
    await transaction.commit();

} catch (err) {
    // Rollback transaction 
    if (transaction) await transaction.rollback();
}


Upvotes: 3

Related Questions