Any example of WebSockets and Loopback?

1,750 views
Skip to first unread message

André Mazayev

unread,
Dec 14, 2016, 3:22:46 PM12/14/16
to LoopbackJS
Hi everyone

Is there any basic and preferably well documented example of WebSockets and Loopback?

I'm asking this because the Publish-subscribe messaging (https://loopback.io/doc/en/lb2/Publish-subscribe-messaging.html) says Warning: The StrongLoop pub-sub modules are not yet at version 1.0. The API and behavior will most likely change before the 1.0 release.

I'm looking for something simple, like an example with a single model (for example a ParkingLot) with a single property (for example number of cars). Then a client can just subscribe to this resource and be notified when it changes.

Thanks in advance


Mark Johnson

unread,
Dec 15, 2016, 5:48:07 PM12/15/16
to LoopbackJS
Our websocket service is an independent application but does make calls to the loopback API as well as Redis pubsub.  It might be worth considering something similar, with a websocket application as a microservice that uses the Loopback REST API.

André Mazayev

unread,
Dec 16, 2016, 6:32:13 AM12/16/16
to LoopbackJS
Thanks for your answer Mark.

Are you from development team? If yes, do you have any plans of implementing this? I think that this feature would be really important in IoT applications where values (for example sensor readings) are constantly changing.

Mark Johnson

unread,
Dec 16, 2016, 4:50:08 PM12/16/16
to LoopbackJS
No, not the Strongloop team.  We've just implemented this differently in our own application stack.  IMO websockets are part of a specialised requirement and shouldn't belong in the Loopback framework, although a pluggable component may make more sense.

André Mazayev

unread,
Dec 20, 2016, 10:17:46 AM12/20/16
to LoopbackJS
Thanks again Mark.

I got another question for you if you don't mind. I'm implementing WebSockets in my own. I'm using WS package. Right now my ./server/server.js file looks like this:

'use strict';

var loopback = require('loopback');
var boot = require('loopback-boot');
var wsServer = require("./websockets");

var app = module.exports = loopback();

.
.
.

// Bootstrap the application, configure models, datasources and middleware.
// Sub-apps like REST API are mounted via boot scripts.
boot(app, __dirname, function (err) {
  if (err) throw err;

  // start the server if `$ node server.js`
  if (require.main === module) {

    //Default
    //app.start();

    //Add WebSockets server
    wsServer.listen(app.start(), app);
  }
});

My websocket file (located at ./server/websockets.js) looks like this:

exports.listen = function (server, app) {
    var wss = new WebSocketServer({ server: server });

    console.info('WebSocket server started...');

    wss.on("connection", function (ws) {
        var reqURL = url.parse(ws.upgradeReq.url, true);

        console.log("Request From WebSockets Client");
        console.log(reqURL);

        //Operation hooks
        //Trigered every time the property is modified (created, updated)        
        var ParkingLot = app.models.ParkingLot;
        ParkingLot.observe("before save", function changes (ctx, next) {
            var data;
             if (ctx.instance) {
                console.log('About to save an instance:\n', ctx.instance);
                data = ctx.instance;
            } else {
                console.log('About to update resources that match the query %j:', ctx.where);
                console.log("Parameters to Update", ctx.data);
                data = {};
                data.where = ctx.where;
                data.data = ctx.data;
            }

            ws.send(JSON.stringify({ 'Changes': data }));
            next();
        });

        ws.send(JSON.stringify({ 'Message': 'Connection established' }));
    });
};

I'm using the Operation Hooks to observe any changes that are made to the ParkingLot model and send them to the subscriber.

This actually works and I can successfully subscribe and receive notifications but this approach does not seem very practical.

A more elegant approach would be to implement Operation Hooks in ./common/models/parkinglot.js and then pass the ctx value to the websocket server and then send it. However, I don't know how can access the ctx outside the Operation Hook.

Is there a way to do it? If so, how?

johncar...@gmail.com

unread,
Jul 1, 2018, 2:22:06 PM7/1/18
to LoopbackJS
Hi Andre,
 
    I was working on something similar and wanted to use websockets and loopback along with angular frontend. Were you able to find the right approach for this?

Thanks,
John

John Gwinner

unread,
Mar 1, 2019, 2:48:27 PM3/1/19
to LoopbackJS
Hi folks. Tagging on as well.
 
We are dealing with IoT data. We have the data showing up, but of course you have to hit 'refresh' to see the new data.

I'd seen that Loopback does Pub/Subscribe, and I guess I'd naively thought that we could just 'subscribe' to a Loopback data model, and instead of periodically doing a GET on the Loopback API, we'd get data pushed via an Angular promise or something. Like the data comes in anyway! 

To me, it seems like Pub/Sub has little to do with loopback.  The examples are for text messages? I mean, we already have a data connection to the server via the API, now we have to open some other port and run some other blasted service on our little IOT device? We've already got a connection and server and API! 

I'm investigating alternates.

Are there any other REST or API client side packages that allow this aside from the Loopback client?

        == John ==
Reply all
Reply to author
Forward
0 new messages