My real question is: Is it possible to work with sequelize having the Models in separate folders?
I'm asking this because i'm trying to work with a modular structure in my application, to accomplish that i need to have the model, the controller and the routes in the same folder, here's what i mean:
├── node_modules
├── src
│ ├── client
│ │ └── ... //Frontend things managed by angular (like views, etc...)
│ └── server
| ├── components
| | ├── db
| | | ├── migrations
| | | | ├── users.js
| | | | └── ...
| | | ├── seeders
| | | ├── config.json
| | | ├── options.json
| | | └── index.js
| | ├── env
| | └── ...
│ ├── modules //By module i mean an entity
| | ├── users
| | | ├── users.model.js
| | | ├── users.controller.js
| | | └── index.js //Here i define the routes
| | └── ...
| └── ...
|
├── package.json
└── server.js
How could i do that? how could i split the models into separate folders?
Maybe what i'm asking for is: How could i configure the models/index.js script to read the models from each directory?
models/index.js
'use strict';
var fs = require('fs');
var path = require('path');
var Sequelize = require('sequelize');
var basename = path.basename(module.filename);
var env = process.env.NODE_ENV || 'development';
var config = require(__dirname + '/../config.json')[env];
var db = {};
if (config.use_env_variable) {
var sequelize = new Sequelize(process.env[config.use_env_variable]);
} else {
var sequelize = new Sequelize(config.database, config.username, config.password, config);
}
fs
.readdirSync(__dirname)
.filter(function(file) {
return (file.indexOf('.') !== 0) && (file !== basename);
})
.forEach(function(file) {
if (file.slice(-3) !== '.js') return;
var model = sequelize['import'](path.join(__dirname, file));
db[model.name] = model;
});
Object.keys(db).forEach(function(modelName) {
if (db[modelName].associate) {
db[modelName].associate(db);
}
});
db.sequelize = sequelize;
db.Sequelize = Sequelize;
module.exports = db;
Something i was thinking is to look for the xxx.model.js under each folder of the modules directory having a structure like this:
modules
├── index.js //The above script configured to read the x.model.js in each folder
├── users
| ├── users.model.js
| ├── users.controller.js
| └── ...
├── questions
| ├── questions.model.js
| ├── questions.controller.js
| └── ...
└── ...
NOTE: I come from a Laravel background, i'm guessing how are migrations and models different in sequelize since when you define a model you tell the type, etc.. of the column, the same as the migration...