I've a model called Collection.js
and it looks like this:
module.exports = {
attributes: {
title: {
type: 'string',
required: true
},
description: {
type: 'text',
required: false
},
sessions: {
collection: 'session',
via: 'collection'
}
}
}
As I understand this document, the message, which is sent via the socket when a new model instance was created, is available through the models name.
So I have this snipped in my app.coffee
file:
socket = io.connect()
socket.on 'collection', ->
console.log 'hey'
I've validated that the 'environment' works, because I get notifications on socket.on 'connect'. -> console.log 'hey'
, but I don't get any for model events like create or destory a record!
Blueprints are activated. What do I have to change?
Here some more code, how I want to use it:
$('document').ready ->
noData = $('#list tr')
socket.get '/collection', (res) ->
createList(res)
So, the socket should be subscribed to all events.
Later I want to hook on this events:
socket.on 'collection', (res) ->
socket.get '/collection', (res) ->
recreateList(res)
But get never notified.
My controller CollectionController.js
looks like:
module.exports = {
manage: function(req, res) {
Collection.watch(req);
return res.view();
}
}
By default, you will be subscribed to all the instances returned by the find
blueprint when you do socket.get('/collection')
, so you should be notified when any of them are updated or destroyed. However, you won't get notifications about records being created unless you either a) explicitly call Collection.watch(req)
in your Sails code, or b) set autoWatch
to true in /config/blueprints.js
. See the reference for .watch() and .subscribe() for more info.
The general idea is that for a large-scale app that could have thousands or millions of users, it doesn't make sense to send out notifications to every connected socket whenever a new user is created. Sockets should only be notified about changes to instances they specifically subscribed to.
Update
After finally getting to review the code in question, it looks like there are a few things going on that need attention:
Collection
, but it needs to be collection
. Collection
is the model's globalized ID, but collection
is its identity, which is used as the event name. Case matters here.autoWatch
setting in /config/blueprints.js
is case sensitive; you have it as autowatch
.socket.post(url, data, callback)
). This allow you to respond differently to actions that you triggered yourself, rather than ones that were triggered by someone else. If you really want to get your own socket notifications from the blueprints, you can set mirror: true
in /config/blueprints.js
.It looks like mirror
needs to be added to the docs, although it's mainly a dev tool that you may regret using in production ;)
Once I changed those three things, the code worked fine!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With