Reputation: 3414
In my node app, I'm defining models (using Sequelize ORM) in two different files: models/app-acl.js and models/app-models.js;
then I'm importing them in a third file (models.js) where I'm defining the relationships between models:
//file models.js
var aclModel = require('./app-acl.js');
var appModel = require('./app-models.js');
//defining relationships...
aclModel.Group.hasMany(aclModel.User, {onDelete: 'CASCADE'});
...
//exporting models:
module.exports = {
aclModel: aclModel,
appModel: appModel
}
Doing this, in other parts of the app I can do
var models = require('models/models.js')
and access all models by models.aclModel... and models.appModel
The thing is that sometimes I need to do operation on arbitrary model, such as a "find" without knowing if it is a aclModel or a appModel; so I would like to export both under the same name; something like:
module.exports = {
models: aclModel + appModel //merged together
}
by this I would be able to do
models[name].find.....
being "name" a model from aclModel or from appModel, and it will work in both cases;
I thought to merge together aclModel and appModel in model.js before exporting like this:
function merge (destination, source) {
for (var property in source)
destination[property] = source[property];
return destination;
}
module.exports = {
models: merge(aclModel, appModel)
}
but this doesn't work; does anybody have a solution for doing this?
Upvotes: 0
Views: 336
Reputation: 11
Maybe you can use :
module.exports = {
...aclModel,
...appModel
}
it is a sample method
Upvotes: 0
Reputation: 145994
OK, after clarifying your question in the comments (next time save everyone's time by including a real program that expresses your question not just snippets and ellipses), my first thought is your design is probably ultimately misguided but nonetheless is achievable and straightforward in javascript.
Put your files in this structure:
models/index.js
models/acl-model.js
models/app-model.js
In your models/index.js
do this:
var _ = require('lodash');
_.extend(module.exports, require('./acl-model'), require('./app-model'));
This will combine all the properties of your two model modules into the index module. In case of a name duplication conflict, the last one will win.
Then you can get a reference to the index with require('models');
or a specific one with require('models/acl-model');
. The index.js
one will support models[name]
dynamic property lookup access. Thus you can do:
var models = require('models');
var name = "Group";
models[name].find();
As long as one of your model modules has a model called "Group", that will work.
Upvotes: 1