Search code examples
javascriptsocketcluster

Send message to socketcluster channel from outside worker


There is an external resource I am watching and whenever the data changes I would like to send a message to a specific channel depending on the data.

I found two ways to do this by bonking my head repeatedly against the SC docs:

  • by watching from the workers, which is not ideal because when there are 1000 clients online the external data source gets hammered with requests from each worker

  • from a client, this is not ideal because i have to subscribe to the channel, send my message, then unsubscribe

How can I do this from within server.js?


Solution

  • A good example I have of sending data or a message when an external resource is changed, is for that external resource (like a website) to call your socket cluster on/emit through the standard way:

    socket.on('documents/upload-file', function (data, respond) {
        documents.uploadFile(data, respond, socket);
    });
    
    • documents.uploadFile I use to upload a file with a base64 string.
    • I then save it file and store the document into the database.
    • The code the call a functiondocuments.getFileList which pull all the document info from the db
    • then that data is publish over a channel:

    socket.exchange.publish('channels/documentList', updatedDocumentList);

    The whole point of a worker is to handle external incoming events. Without knowing what your external resource is then I can't specifically say if this is the best approach for you, but hopefully it's a good place to start with.