api/ws

module:api/ws

Description:
  • WebSockets messages as API routes

    To enable websockets configure api-ws-port to the same value as the HTTP port or other number, eg api-ws-port = 8000

    In the browser

    Open a socket first

    var ws = new WebSocket("http://localhost:8000/ws?id=123");
    ws.onmessage = (msg) => { console.log(msg) }
    

    There are two ways to send messages via WebSockets to the server from a browser:

    1. as URLs

    ws.send('/project/update?id=1&name=Test2')
    

    This is a GET request, if users middleware is enabled and matches it will be checked for access and authorization before letting it pass via routes. This method allows to share the same route handlers between HTTP and WebSockets requests, the handlers will use the same code and all responses will be sent back, only in the WebSockets case the response will arrive in the message listener onmessage (see above)

    If not authorized the connection will be dropped.

    2. as JSON objects, message format can be any

    ws.send({ op: "/project/update", project: { id: 1, name: "Test2" } })```
    

    This is a POST request, such requests use the original the path which was used during the connect, i.e. the one used in the above is /ws. The router handler for this path will receive all POST messages from WebSocket clients, parse the JSON and place it in the body if the middleware is enabled, same router routes as with regular HTTP requests.

    In the server

    All WebSocket messages sent from the server will arrive in the event handler and must be formatted properly in order to distinguish what is what, this is up to the application logic.

    If the server needs to send a message to all or some specific clients for example due to some updates in the DB, it must use the module:api/ws.notify function.

    // Notify all clients who is using the project being updated, the JSON format is for demo purposes
    api.app.all("/ws", (context) => {
       switch (context.query.op) {
       case "/project/update":
          //  some code ....
          api.ws.notify({ query: { id: context.query.project.id } }, { op: "/project/update", project: context.query.project });
          break;
       }
       context.send(200);
    });
    
    // Received a new message for a user from external API service, notify all WebSocket clients by user id
    api.app.post("/api/message", (context) => {
       ....
       ... processing logic
       ....
       api.ws.notify({ user: { id: context.user.id } }, { op: "/message/new", msg: context.query.msg });
    });
    
Source:

Members

(static) port :int

Description:
  • port to listen for messsages, can be the same as the main HTTP port

Source:

Methods

(static) broadcast(options, msg)

Description:
  • Send a message to all WebSockets inside an api process that match the criteria from the options

Source:
Parameters:
Name Type Description
options object
Properties
Name Type Attributes Description
wsid string | Array.<string> <optional>

send to the specific WebSocket(s), can be a list

path RegExp <optional>

a regexp to match initial WebSocket connection path

user object <optional>

an object to be used for condition against WebSocket's authenticated user, module:lib.isMatched is used for comparison

query object <optional>

an object to be used for condition against WebSocket's initial query, module:lib.isMatched is used for comparison

preprocess function() <optional>

a function(ws, options, msg) to be called before sending in order to possibly modify the message for this particular user, i.e. for permissions checks, if it needs to be modified return a copy otherwise the original will be used, returning null will skip this socket

msg object | string

(static) notify(options, msg, callbackopt) → {boolean}

Description:
  • Broadcast a message to all matching connected clients

    • in local mode it sends only to the clients inside a single process
    • if `api-ws-queue`` is defined then all api processes listening on that queue will notify matching clients directly using module:api/ws.broadcast
Source:
Parameters:
Name Type Attributes Description
options object
msg object | string
callback function() <optional>
Returns:
Type Description
boolean
  • false if not sent