Open tlvenn opened 10 years ago
Hmmm... tbh, I haven't tried to use this part of Thinky yet. It seems the best way to do this would be to setup the model dependencies after this plugin has been loaded. E.g.
plugin.plugins['hapi-rethinkdb-thinky'].Event.belongsTo(plugin.plugins['hapi-rethinkdb-thinky'].Venue);
Ideally you'd be able to put these dependency definitions within the model files themselves but I haven't figured out a nice way to follow the pattern on thinky.io where the Thinky configuration can be imported into each model. Do you have any ideas?
Unfortunately I dont know enough about Node internals regarding its modules to answer that. I believe that @neumino leverages how Node is using partial copy of module to avoid circular dependencies and defining a model twice but I have no idea if this can be leveraged if the constructor method is used.
We could probably ask him if he has an idea about this.
I'm not super familiar with Hapi even though I've heard about it quite a few times but from what I saw, I think one way to do it would be to expose all the models first, and in a second time expose all the relations.
I'm not sure if you all have figured out a better way to do this, but here's what I'm doing in my application in case it helps. I have separate plugins for each model, and the actual model file is a factory function that accepts thinky (which is also contained in its own plugin) as a dependency. After all of the plugins in my app have finished registering, I call a function which I expose in my thinky plugin to define all model relations:
exports.register = function (server, options, next) {
var thinky = require('thinky')(options);
server.expose('orm', thinky);
// This should be called after all plugins are registered
// and before the server is started
server.expose('relations', function (server, next) {
for (var name in server.plugins) {
var plugin = server.plugins[name];
if (plugin.hasOwnProperty('model') &&
plugin.hasOwnProperty('relations')) {
plugin.relations(server.plugins);
}
}
next();
});
next();
};
The model files themselves export a method called relations
when applicable. That method (which is referenced in the above code) looks like this:
relations: function (plugins) {
var ModelOne = this.model; // we are currently in this model's module file
var ModelTwo = plugins.course.model; // passed in via the above code snippet
ModelOne.belongsTo(ModelTwo, 'modeltwo', 'modelTwoId', 'id');
}
This way the model files themselves describe their relations. This is as close as I could get to the architecture described in http://thinky.io/documentation/architecture/ while using hapi plugins.
Hi,
Given that your model modules are using a constructor, how do you structure it so that you can add associations without having issue with circular dependencies ?
Similar to the example in http://thinky.io/documentation/architecture An example with 2 models would be great.
Thanks in advance.