Stop using `sequelize.import`
papb opened this issue ยท 7 comments
This repository uses sequelize.import
:
https://github.com/sequelize/express-example/blob/master/models/index.js
However sequelize.import
was deprecated and is already removed in v6 beta.
Related: sequelize/cli#895
As documentation here https://sequelize.org/master/manual/models-definition.html show that it is deprecated.
The documentation suggests to use require, But i am not sure how to use it.
can you provide a small snippet.
//load all Models from models directory dynamically
fs.readdirSync(__dirname).filter(file => {
return (file.indexOf('.') !== 0) && (file !== path.basename(__filename)) && (file.slice(-3) === '.js');
}).forEach(function (filename) {
database.import(path.join(__dirname, '', filename));
});
const models = database.models;
// Set up data relationships
Object.keys(models).forEach(name => {
if ('associate' in models[name]) {
models[name].associate(models);
}
});
Here is an example using require
./models/index.js
const dotenv = require('dotenv');
const fs = require('fs');
const path = require('path');
const { Sequelize, DataTypes } = require('sequelize');
const filebasename = path.basename(__filename);
const db = {};
// Get env var from .env
dotenv.config()
const { DB_HOST, DB_USER, DB_PASS, DB_NAME, DB_FORCE_RESTART } = process.env;
const config = {
host: DB_HOST,
dialect: 'mysql',
dialectOptions: {
charset: 'utf8',
}
}
const sequelize = new Sequelize(DB_NAME, DB_USER, DB_PASS, config);
fs
.readdirSync(__dirname)
.filter((file) => {
const returnFile = (file.indexOf('.') !== 0)
&& (file !== filebasename)
&& (file.slice(-3) === '.js');
return returnFile;
})
.forEach((file) => {
const model = require(path.join(__dirname, file))(sequelize, DataTypes)
db[model.name] = model;
});
Object.keys(db).forEach((modelName) => {
if (db[modelName].associate) {
db[modelName].associate(db);
}
});
db.sequelize = sequelize;
db.Sequelize = Sequelize;
const sequelizeOptions = { logging: console.log, };
// Removes all tables and recreates them (only available if env is not in production)
if (DB_FORCE_RESTART === 'true' && process.env.ENV !== 'production') {
sequelizeOptions.force = true;
}
sequelize.sync(sequelizeOptions)
.catch((err) => {
console.log(err);
process.exit();
});
module.exports = db;
./models/User.js
'use strict';
import cryp from 'crypto';
module.exports = function (sequelize, DataTypes) {
const User = sequelize.define('User', {
email: {
type: DataTypes.STRING(50),
allowNull: false,
unique: true,
validate: {
isEmail: { msg: "Please enter a valid email addresss" }
},
isEmail: true
},
password_hash: { type: DataTypes.STRING(80), allowNull: false },
password: {
type: DataTypes.VIRTUAL,
set: function (val) {
//this.setDataValue('password', val); // Remember to set the data value, otherwise it won't be validated
this.setDataValue('password_hash', cryp.createHash("md5").update(val).digest("hex"));
},
validate: {
isLongEnough: function (val) {
if (val.length < 8) {
throw new Error("Please choose a longer password");
}
}
}
},
role: {
type: DataTypes.INTEGER,
allowNull: false
},
active: {
type: DataTypes.INTEGER,
allowNull: false,
defaultValue: 1
}
}, {
classMethods: {
associate: function (models) {
// User.belongsTo(models.Department, { foreignKey: { allowNull: false } });
// User.belongsTo(models.Position, { foreignKey: { allowNull: false } });
// User.belongsTo(models.Profile, { foreignKey: { allowNull: false } });
// User.hasMany(models.Report, { foreignKey: { allowNull: false } });
// User.hasMany(models.Notification, { foreignKey: { allowNull: false } });
// User.hasMany(models.Response, { foreignKey: { allowNull: false } });
}
},
timestamps: true,
// don't delete database entries but set the newly added attribute deletedAt
// to the current date (when deletion was done). paranoid will only work if
// timestamps are enabled
paranoid: false,
// don't use camelcase for automatically added attributes but underscore style
// so updatedAt will be updated_at
underscored: true
});
return User;
};
.env
DB_HOST=localhost
DB_USER=wilo087
DB_PASS=temp
DB_NAME=database_name
DB_FORCE_RESTART=true #Remove and create tables
Full example on:
https://github.com/wilo087/pethome_raffle_backend/tree/develop
This solution reading files from the filesystem seems so nasty to me.
What about an index in the models folder?
I can make a PR.
You can use only index file on the model folder, but, what happens if you have more than 30 models with associations, validations functions, hooks, virtual fields, etc.?
Exactly, your code going to look nasty as f**k.
Hello everyone, I created a new example from scratch. The new example does not use sequelize.import
anymore.
using require() assumes that the package in question isn't using ES5-6 syntax. require isn't a thing in ES modules. What would I use as an alternative then?
If you're using esm, use import
. Sequelize works with both module systems, but this boilerplate is written in cjs