Skip to content

Instantly share code, notes, and snippets.

@der-On
Created June 20, 2015 07:20
Show Gist options
  • Save der-On/358375f0f5d6a93c5bbc to your computer and use it in GitHub Desktop.
Save der-On/358375f0f5d6a93c5bbc to your computer and use it in GitHub Desktop.
Improve model associations with loader methods and promises
/**
* Adds a loader method to the model innstance that will automatically populate the property for the assoc after load
* Example: this.belongsTo('User') will add a "loadUser" method
* @param instance
*/
module.exports.improveAssocs = function(instance)
{
var model = getModel();
var type = instance.type;
var def = model.descriptionRegistry[type];
Object.keys(def.associations).forEach(function(assocType) {
Object.keys(def.associations[assocType]).forEach(function(name) {
var assoc = def.associations[assocType][name];
var fnName = utilities.string.getInflection(assoc.name, 'constructor', (assocType === 'hasMany') ? 'plural' : 'singular');
var loader = 'load' + fnName;
var promise = 'load' + fnName + 'Promise';
var getter = 'get' + fnName;
var prop = utilities.string.getInflection(assoc.name, 'property', (assocType === 'hasMany') ? 'plural' : 'singular');
// create assoc prop with empty value/array
instance[prop] = (assocType === 'hasMany') ? [] : null;
// now override getter to automatically set property
instance[loader] = function(cb) {
instance[getter](function(err, data) {
instance[prop] = data;
cb(err, data);
});
};
// also add a promise method
instance[promise] = promisifyModels.promisify(instance, loader);
});
});
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment