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

时间:2017-09-09 06:13:47

标签: node.js loopbackjs strongloop loopback

有没有办法控制或监控特定模型的回送insert operation以及插入调用函数后?例如: 提交表单if表单成功插入后,验证邮件会发送到输入的邮件地址或短信输入的电话号码

'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);
});

1 个答案:

答案 0 :(得分:3)

如果您想使用特定型号,请使用Operation hooks

您拥有'保存前'和'保存后',您可以运行任何其他逻辑,例如发送电子邮件。

./服务器/我的-mode.js

[info] Running com.abhi.ClockGrpcClient failed with error io.grpc.StatusRuntimeException: CANCELLED: Failed to read message

./服务器/我的-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();
});