Last active
February 16, 2017 01:01
-
-
Save bitmage/8930310e45466f1e6f57 to your computer and use it in GitHub Desktop.
Loopback Model - afterCreate hook to auto-save related models instantiated using build()
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Model hooks are deprecated. with the new operation hook pattern :