我需要以编程方式为模型运行远程挂钩。我怎样才能做到这一点?

最佳答案

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

/**
 * 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);

关于node.js - Node.js +回送:以编程方式运行远程 Hook ,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/36926893/

10-12 15:45