Node.js + Loopback:以编程方式运行远程钩子

时间:2016-04-28 23:01:28

标签: node.js loopbackjs

我需要以编程方式为模型运行远程钩子。我怎么能这样做?

1 个答案:

答案 0 :(得分:0)

我没有找到任何解决方案并实施了我的

/**
 * Trigger execution of remote hooks of a model
 *
 * @param app The loopback application
 * @param modelName The model name
 * @param data The model data
 * @param when The possible values are 'before' or 'after'
 * @param method The remote method name
 * @param ctx The hooks context
 * @param next
 */
exports.execHooks = function(app, modelName, data, when, method, ctx, next) {

  // Save original context values
  var originalData = ctx.args.data || {};
  var originalMethod = ctx.method;

  // Get shared method
  var modelSharedClass = app.remotes().classes().filter(function(item) {
    return item.name === modelName;
  })[0];
  var modelSharedMethod = modelSharedClass.methods().filter(function(item) {
    return item.name === method;
  })[0];

  // Change context data
  ctx.args.data = data;
  ctx.method = modelSharedMethod;
  ctx.methodString = modelSharedMethod.stringName;

  // Execute hooks
  var remoteObject = app.remoteObjects()[modelName];
  app.remotes().execHooks(when, modelSharedMethod, remoteObject, ctx, function(err) {

    // Restore context data
    var changedData = ctx.args.data;
    ctx.args.data = originalData;
    ctx.method = originalMethod;
    ctx.methodString = originalMethod.stringName;

    next(err);
  });
};

使用示例:

utils.execHooks(app, app.models.MyModel, model, 'before', 'create', ctx);