Skip to content

Instantly share code, notes, and snippets.

@bitmage
Last active February 16, 2017 01:01
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save bitmage/8930310e45466f1e6f57 to your computer and use it in GitHub Desktop.
Save bitmage/8930310e45466f1e6f57 to your computer and use it in GitHub Desktop.
Loopback Model - afterCreate hook to auto-save related models instantiated using build()
var async = require('async');
Project.afterCreate = function(done) {
var self = this;
function createRelation(rel, next, name) {
self[name].create(rel, next);
};
objMapAsync(this.__cachedRelations, createRelation, done);
};
// for reference, this is just a helper function I created
// the map included in async only works with arrays
// this one works with objects
function objMapAsync(obj, iter, done) {
function wrappedIter(results, key, next) {
function interpret(err, result) {
results[key] = result;
next(err, results);
};
iter(obj[key], interpret, key);
};
async.reduce(Object.keys(obj), {}, wrappedIter, done);
}
@zeriss
Copy link

zeriss commented Sep 2, 2016

Model hooks are deprecated. with the new operation hook pattern :

Project.observe('after save', function(ctx,next) {
      if (ctx.instance) {
          objMapAsync(ctx.instance.__cachedRelations, createRelation, next);
      }
      function createRelation(rel, next, name) {
          ctx.instance[name].create(rel, next);
      };
      next();
});

function objMapAsync(obj, iter, done) {
      function wrappedIter(results, key, next) {
        function interpret(err, result) {
          results[key] = result;
          next(err, results);
        };
        iter(obj[key], interpret, key);
      };
      async.reduce(Object.keys(obj), {}, wrappedIter, done);

    }

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment