Sails.js sails.io.js, blueprints not getting events from .publish(), how to subscribe to all events?

49 Views Asked by At

I don't know why I'm not getting notification events from sails models from model.publish(). In pre-1.x sailsjs, similar client-side code had worked and I would get every event when records are created, updated or deleted. So, I must be misunderstanding something.

How do I subscribe to all events for any records from CRUD operations?

On the server side, I have Job.js and JobController.js.

In Job.js model, this test just creates a new record every 10 secs:

test: async function(dataset) {
    let count = 0;
    setInterval(async function() {
        count++;
        let newjob = {
            dataset: dataset,
            state: 'delayed',
            name: "job name "+count
        };
        
        let job = await Job.create(newjob).fetch()
        sails.log.info('created test job: ',JSON.stringify(job));
        Job.publish([job.id],job);

    },10000);

}

In JobController.js, called by the client and starts the test rolling:

submittest: async function(req,res) {

    let dataset = await Dataset.Get({});
    await Job.test(dataset[0].id);

    return res.ok({status:'ok'});
}

In the client test.html, io.socket.get operations are successful, but I never see an event:

...
<script>
io.socket.get('/job', function(body, JWR) {

  console.log('and with status code: ', JWR.statusCode);

  setTimeout(function() {
    io.socket.get('/job/submittest', function (body,JWR) {

      io.socket.on('job', function(msg) {
        console.log("job event",msg);  // not getting here.  why?
      });

    });
  },2000)

});
</script>

This all runs fine but the problem is, no events are seen from the client side. Why? Am I not subscribed to events with the initial io.socket.get('/job')?

1

There are 1 best solutions below

0
NeoNexus DeMortis On

Essentially, what is happening here, is you are shouting into an empty box about a new record in your model, but no one is listening to you in that empty box.

In other words, you need to subscribe the socket connection to the model updates.

See: https://sailsjs.com/documentation/reference/web-sockets/resourceful-pub-sub/subscribe

Also, checkout the answer to this question for a quick how to.