Huge News!Announcing our $40M Series B led by Abstract Ventures.Learn More
Socket
Sign inDemoInstall
Socket

publication-server

Package Overview
Dependencies
Maintainers
1
Versions
35
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

publication-server

publication-server =====

  • 1.4.3
  • Source
  • npm
  • Socket score

Version published
Weekly downloads
15
decreased by-21.05%
Maintainers
1
Weekly downloads
 
Created
Source

publication-server

Usage

In order to be able to mount a WebSocket server on the same port as an Express server, we need to get the http server from the app so that we can expose it to the WebSocket server. As an example:

var express = require('express');
var PublicationServer = require('publication-server');

var app = express();
var server = require('http').createServer(app);
var errHandler = function(err) {
  console.log(err.error);
};

var pubServer = new PublicationServer({
  authFn: authenticationFunction,
  mountPath: '/ws',
  server,
  errHandler
});

// ...

server.listen(process.env.PORT || '8080');
Authentication function

One plus of this server is that it can authenticate WebSocket requests via the headers on the initial UPGRADE request. This is done in the REQUIRED authentication function that is passed to the publication-server constructor. This authentication function takes two parameters which are the originating HTTP UPGRADE request and a callback. The callback has the following signature:

/**
 * This callback is called to signal that we've either authenticated the
 * incoming HTTP UPGRADE request or we've rejected it.
 *
 * @param {Error} err The error that we've returned to signify why the user
 *    failed authentication. If `err` is null we've successfully authenticated
 *    the incoming connection to upgrade into a WebSocket.
 * @param {String} userId An optional unique tag to identify a user by. It is
 *    exposed inside of publications at `this.userId`. Some publications may
 *    not require this value, which is why it is optional to return, although
 *    it is highly encouraged to return a `userId` to be set.
 */
function done (err, userId) {}

The authorization function would have the following flow then:

function authenticationFunction(req, done) {
  // Logic checking the websocket headers, etc.
  // ...

  // If the request failed authentication, return an error.
  if (failedAuth) process.nextTick(done, new Error('failed to authenticate user'));

  // If the request passed authentication, call the callback with the the ID
  // of the user that we've authenticated.
  process.nextTick(done, null, `SUPERUSER$12345`);
}
Registering publications
var pubSub = require('./path/to/initialized/server');

pubSub.publish('PublicationName', function() {

});
Marking a publication as ready

Whenever a publication has finished publishing the initial documents that it needs to send, it must mark itself as ready. This is accomplished by calling this.ready().

pubSub.publish('PublicationName', function() {

  // Initial document publishing.
  this.ready();

  // Add future event handlers if desired.
});
Errors inside a publication

If we encounter an error prior to marking a publication as ready, we should pass the error to this.error(). This will call the registered error handler, and pass the error along to the client.

pubSub.publish('PublicationName', function() {
  this.error(new Error('failed to do something require'));
});
Error handling

Errors passed to the error handler provided upon server initialization are objects with there properties:

  • error: The original error that was reported by the publication.
  • userId: The ID of the user who was subscribing to the publication when the error occurred
  • extra: Any extra information that was recorded - currently this is the parameters that were provided to the publication.

Gracefully shutting down

The publication server also exposes a shutdown function which accepts an optional timeout, within which it is expected to close all current websocket connections. The timeout within which to gracefully shutdown defaults to zero if none is provided. Also note that the unit is in milliseconds. As an example:

// This gives the server 10 seconds to gracefully shutdown.
pubSub.shutdown(10000);

Client

See publication-client for the client for this server.

Changelog

  • 1.4.3 Delete subscription references client side when we unsubscribe from a publication.
  • 1.4.2 Fix typo with unsubscribe message.
  • 1.4.1 Handle subscription initialization errors.
  • 1.4.0 Handle custom event broadcasting (for shutdown message specifically).
  • 1.3.0 All shutdown options to be passed through to Primus.
  • 1.2.1 Enforce message ordering to the client.
  • 1.1.1 Fix bad ObjectUtils reference.
  • 1.1.0 Alter how we wrap the authentication function and make it required.
  • 1.0.0 Initial release of server and client

Keywords

FAQs

Package last updated on 08 Mar 2017

Did you know?

Socket

Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.

Install

Related posts

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap
  • Changelog

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc