2
votes

Is there any way to control or monitor loopback insert operation for specific model and after insert call a function? for example: after submitting a form if form successfully inserted a verification mail sends to entered mail address or SMS to entered phone number

'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
you could use mixins and add them to every model you want to observe - Victor Godoy
hi @victor-godoy, tnx .I will be appriciated if you could guide me more. - RSA
with mixins you can extends additional logic to any Model but for your case I suggest to use Operation hooks loopback.io/doc/en/lb3/Operation-hooks.html - Victor Godoy

1 Answers

3
votes

If you want to for a specific Model you should use Operation hooks

You have the 'before save' and 'after save' there you can run any additional logic you want like send the email.

./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();
});