Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Run sequelize model hooks when seeding

I'm currently trying to seed a postgresql database with sequelize, I have hooks declared on my model that work just fine when creating separate records (e.g. tests)

Does the data in my seed file need to be as how would show in the final table or can I call the hooks when creating?

Here are my files:

/*users-seed.js*/
'use strict'

module.exports = {
  up: function (queryInterface, Sequelize) {
    return queryInterface.bulkInsert('Users', [/*users-data*/])
  },
  down: function (queryInterface, Sequelize) {
    return queryInterface.bulkDelete('Users', null, {})
  }
}

And

/*user.js*/
module.exports = function (sequelize, DataTypes) {
  let User = sequelize.define('User', {
    /* user attributes */
  }, {
      instanceMethods: {
        hashPassword: function (password) {
          return bcrypt.hash(password, 15)
        },
        hashEmail: function (email) {
          return crypto.createHash('sha256').update(email).digest('hex')
        }
      },
      hooks: {
        beforeCreate: function (user) {
          return user.hashPassword(user.password_digest).then(function (hashedPassword) {
            user.email = user.hashEmail(user.email)
            user.password_digest = hashedPassword
          }).catch(e => { console.log('e', e); throw new Error(e) })
        },
        beforeBulkCreate: function (users) {
          return users.forEach(function (user) {
           return user.hashPassword(user.password_digest).then(function (hashedPassword) {
              user.email = user.hashEmail(user.email)
              user.password_digest = hashedPassword
            }).catch(e => { console.log('e', e); throw new Error(e) })
         })
        }
      }
    })
  return User
}
like image 743
Omar Vazquez Avatar asked Oct 18 '22 18:10

Omar Vazquez


1 Answers

Ok so it was a mistake of mine, I missunderstood how queryInterface.bulkInsert() works, I thought it called the model hooks before "insert" (yes, this is what I missunderstood) them in the database, it inserts the raw data you put in the string, I think that is why in the docs the hooks are showed with a model instance using bulkCreate, bulkUpdate, etc

like image 169
Omar Vazquez Avatar answered Oct 27 '22 22:10

Omar Vazquez