1

In DerbyJS:

How do I add event listeners to "The Model", only server side, without having to rely on requests (express middleware)?

Related question I've found: How to create server-side application logic on Racer / DerbyJS?

Of course I can write an express middleware. But the "shared" data model would come in really handy if I could access it without having to rely on a request, and I don't know how to do that without having to put the specific code into the shared codebase.

Use case: order processing for e-commerce software

My model could be like this:

{
  orders: [ {
    id: '1',
    products: [ ... ],
    user: [ ... ],
    token: 'stripe credit card token I get from Client here'
  }, {
    ...
  } ]
}

This way the client could place new orders doing

model.at('orders').add(myOrder);

And the server could process it by listening for 'insert' events:

model.on('insert', 'orders', function(captures, index, newOrders) {
  newOrders.forEach(processOrder);
})
Community
  • 1
  • 1
Roman
  • 5,888
  • 26
  • 47

1 Answers1

2

Yes you can!! :)

You have 2 options.

Option 1)

Use app.serverUse to include a server side script, or use the store.js if you have used yo derby-generator. There you can :

var model = dbStore.createModel();
model.subscribe("orders", function(){
  model.on("insert", "orders.**", function() {
   ...
  });
});

Option 2)

Using https://github.com/derbyparty/derby-hook

dbStore.hook('create', 'orders', function(id, doc, session, backend) {
  var model = dbStore.createModel();
  var $order = model.at('orders.'+ id);
   ...
});
Rui Gonçalves
  • 1,164
  • 8
  • 15
  • Actually, in the meantime I have tried both of those. Option 1 results in this: https://github.com/derbyjs/racer/issues/212 Option 2 never fires the create event. I have worked around Option 1, getting it to work, if I subscribe to the model only after a 10 seconds timeout (after the server started). I'll still accept this anser as it is obviously the correct answer "by design". – Roman Mar 09 '15 at 09:46
  • I notice the error you get is related to redis, in my configuration I don't use redis. FYI I am using the latest alpha release of derby, 0.6-alpha41, maybe this helps – Rui Gonçalves Mar 09 '15 at 11:13
  • what does orders.** accomplish vs orders.* ? – msj121 Jun 19 '15 at 03:10
  • "orders.*" listens to shallow (1 level deep) changes, "orders.**" listens to deep changes inside the orders path. – Rui Gonçalves Jun 22 '15 at 10:55