Skip to content

Custom service events #111

@daffl

Description

@daffl

As discussed in #108 it would be nice to allow custom events on services. As an example, a payment service might want to notify the user about the process during payments by emitting log events:

var paymentService = {
  events: [ 'log' ],

  create(data, params) {
    var log = message => this.emit('log', { message: message, user: params.user });
    var errorHandler = error => log(`There was an error processing your payment: ${error.message}`);

    return addCreditCard(data.cc).then(cc => {
      log(`Credit card ${cc.displayName} added successfully`);

      return processPayment(data).then(paymentInfo => {
        log(`Payment of ${paymentInfo.amount}.- successful!`);

        return paymentInfo
      });
    }).fail(errorHandler);
  }
};

app.use('/payments', paymentService);

And on the client we could do:

socket.on('payments log', function(data) {
  $('#payment .logs').append(`<li>${data.message}</li>`);
});

And also generalize event filtering which helps decide to decide what events to dispatch where:

let paymentService = app.service('payments');

paymentService.filter('updated', function(data, params, callback) {
  if(data.company_id !== params.user.company_id) {
    return callback(null, false);
  }

  return callback(null, data);
});

paymentService.filter('log', function(data, params, callback) {
  if(data.user.id !== params.user.id) {
    return callback(null, false);
  }

  return callback(null, data.message);
});

Metadata

Metadata

Assignees

Labels

Type

No type

Projects

No projects

Milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions