3

I have the following Employee model for a MySQL database:

var bcrypt = require('bcrypt');

module.exports = (sequelize, DataTypes) => {
    const Employee = sequelize.define(
        "Employee",
        {
            username: DataTypes.STRING,
            password: DataTypes.STRING,
        }, {}
    );
    return Employee;
};

Seeding the database is done by reading a .sql file containing 10,000+ employees via raw queries:

sequelize.query(mySeedingSqlFileHere);

The problem is that the passwords in the SQL file are plain text and I'd like to use bcrypt to hash them before inserting into the database. I've never done bulk inserts before so I was looking into Sequelize docs for adding a hook to the Employee model, like so:

hooks: {
  beforeBulkCreate: (employees, options) => {
    for (employee in employees) {
      if (employee.password) {
        employee.password = await bcrypt.hash(employee.password, 10);
      }
     }
  }
}

This isn't working as I'm still getting the plain text values after reseeding - should I be looking into another way? I was looking into sequelize capitalize name before saving in database - instance hook

Sean
  • 507
  • 1
  • 9
  • 27

1 Answers1

3

Your hooks won't be called until you use model's function for DB operation , so if you are running raw query , hooks will never be fired,

Reason : You can write anything inside your raw query , select/insert/update/delete anything , how does sequelize.js know that it has to fire the hooks. This is only possible when you use methods like

Model.create();
Model.bulkCreate();
Model.update();
Model.destroy;

And as per DOC raw query doesn't have hooks option to add. And for MODEL queries you can check that it has option to enable/disable hook.

Vivek Doshi
  • 56,649
  • 12
  • 110
  • 122
  • Upvoted but what are the workarounds for this ? Let's say sequelize cannot perform what I want through model (i.e. non raw) sql queries (for example : an upsert operation, https://github.com/sequelize/sequelize/issues/11656) , there's no way to use an afterSave hook after a raw query that does this ? That seems restrictive. :( Let's say I have complex code being re-used through hooks across all our projects, I don't want to duplicate this code elsewhere and not use hooks. :( – Rose Sep 12 '22 at 20:44
  • Perhaps specifying the queryType (https://sequelize.org/api/v6/class/src/sequelize.js~sequelize#instance-method-query) would help in ensuring those hooks are working properly. – Rose Sep 12 '22 at 20:58