npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

publication-server

v3.0.5

Published

### Usage

Downloads

461

Readme

publication-server

Usage

See /examples for example how to use this.

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:

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

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

const 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

const 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. See /examples directory
});

Errors inside a publication

If a publication encounters an error, it 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 these 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.