如何控制环回中的插入操作?

How to control insert operation in loopback?

有没有什么方法可以控制或监视特定型号的环回 insert operation 并在插入调用函数后?例如: 提交表单后 if 表单成功插入验证邮件发送到输入的邮件地址或 SMS 到输入的 phone 号码

'use strict';

var loopback = require('loopback');
var boot = require('loopback-boot');

var app = module.exports = loopback();

app.start = function() {
  // start the web server
  return app.listen(function() {
    app.emit('started');
    var baseUrl = app.get('url').replace(/\/$/, '');
    console.log('Web server listening at: %s', baseUrl);
    if (app.get('loopback-component-explorer')) {
      var explorerPath = app.get('loopback-component-explorer').mountPath;
      console.log('Browse your REST API at %s%s', baseUrl, explorerPath);
    }
  });
};

// Bootstrap the application, configure models, datasources and middleware.
// Sub-apps like REST API are mounted via boot scripts.
boot(app, __dirname, function(err) {
  if (err) throw err;

  // start the server if `$ node server.js`
  if (require.main === module)
    app.start();
});

var properties = {};
var options = {trackChanges: true };

var MyModel = loopback.Model.extend('Registration', properties, options);
MyModel.on('changeed', function(inst) {
  console.log('model with phonenumber %s has been changed', inst.phonenumber);
});

如果您想要特定型号,您应该使用 Operation hooks

你有 'before save' 和 'after save',你可以 运行 任何你想要的附加逻辑,比如发送电子邮件。

./server/my-mode.js

MyModel.observe('before save', function (ctx, next) {
  if (ctx.instance) {
    // When Create (POST)
    // ctx.instance have the json properties
    console.log("Triggers when create");
  } else {
    // When Update (UPDATE)
    // ctx.data have the json properties
    console.log("Triggers when update");
  }
  next();
});

./server/my-mode.js

MyModel.observe('after save', function(ctx, next) {
  if (ctx.instance) {
    // When Create (POST)
    // ctx.instance have the json properties
    console.log("Triggers after create");

  } else {
    // When Update (UPDATE)
    // ctx.data have the json properties
    console.log("Triggers after update");
  }
  next();
});