Loopback: How to control or monitor insert operation in loopback?

Created on 9 Sep 2017  路  1Comment  路  Source: strongloop/loopback

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

Most helpful comment

I would suggest that you define a Remote Method that holds your creation logic, and then add a Remote Hook to intercept it once it's finished, eg:

MyModel.afterRemote('Registration', function(ctx, user, next) { console.log('model with phonenumber %s has been changed', user.phonenumber'); next(); });

PS. You can use wild cards to intercept Remote Hooks, like *.save, and every remote method that ends in 'save' will be intercepted.

>All comments

I would suggest that you define a Remote Method that holds your creation logic, and then add a Remote Hook to intercept it once it's finished, eg:

MyModel.afterRemote('Registration', function(ctx, user, next) { console.log('model with phonenumber %s has been changed', user.phonenumber'); next(); });

PS. You can use wild cards to intercept Remote Hooks, like *.save, and every remote method that ends in 'save' will be intercepted.

Was this page helpful?
0 / 5 - 0 ratings