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-client

v3.2.4

Published

A client for a publication-server

Downloads

254

Readme

publication-client

This module provides a client side module for subscribing to publications from a publication-server.

Installation

$ npm install publication-client

Usage

See usage examples.

Requirements

publication-client is an ES6 module, so you most likely want to use a bundler such as rollup. It also depends on underscore, so make sure that the project using publication-client can resolve underscore, this normally means either:

Initialization

The only required field for creating a client is the host to connect to as a URL. This means that if you have the publication server mounted at wss://sub.domain.tld/websocket we would provide https://sub.domain.tld as the URL param. Also note that you can provide query params to be passed as part of the provided connect URL (i.e. https://sub.domain.tld?foo=bar).

import PublicationClient from 'publication-client';

var client = new PublicationClient(`https://testing.domain.com?foo=bar`);

Checking connection state

The publication client emits a connected event once it has successfully connected.

client.once('connected', () => {
  console.log('connected successfully!');
});

It also emits disconnected event as soon as it becomes disconnected, and will emit a connected event if it is able to successfully connect to the publication server again.

client.on('disconnected', () => {
  console.log('Oh no! Our connection is gone!');

  client.once('connected', () => {
    console.log('Phew! We have a new connection again!');
  });
});

Subscribing

To subscribe to a publication, simply provide the publication name and any parameters for it. The subscription will not begin until the connection has been successfully connected.

client.subscribe('hello', {
  actor: 'world'
});

Subscriptions also can be queried for 'readiness'. They can return a Promise via the whenReady function, and also emit a ready event.

client.subscribe('foo').whenReady().then(() => {
  console.log('subscription is ready!');
});

Likewise, if a subscription fails during initialization, the Promise returned from whenReady will reject with the responsible error and a nosub event will also be emitted.

client.subscribe('noSuchSub').whenReady().catch((err) => {
  console.log(`Subscription failed with err: ${err.message}`);
});

Waiting on initial subscriptions to load

whenReady is provided as a convenience function if you want to be able to wait for a single subscription or for multiple subscriptions to complete before performing some action. For example:

var sub0 = client.subscribe('sub0'),
    sub1 = client.subscribe('sub1'),
    sub2 = client.subscribe('sub2');
Promise.all(_.invoke([sub0, sub1, sub2], 'whenReady')).then(() => {
  console.log('Our initial subscriptions are all ready!');
});

Subscription "readiness" after disconnection

When the client reconnects to the server after being disconnected, the subscription will reset - meaning that whenReady can be queried once again to know when the subscription is ready.

The reason we do this is to allow a consumer to know about the updated state of a subscription after a connection has been broken/down for a long period of time (i.e. a user closed their laptop and re-opened it later). This is necessary because if a connection is down for a significant period of time, we could have missed a very large number of additions, changes and removals to any local collections that our subscription populates. As such, all local collections are cleared of any documents upon reconnection (so that we can ensure that they are then updated with the appropriate state). Another benefit of this approach is that any pre-exising reactive queries on local collection do not need to be re-created, they will still function as desired.

Note that similarly to how a subscription emits ready when it is ready, after the client has been disconnected and a subscription is ready after re-subscription, it will again emit a ready event.

Subscription errors after initialization

After a subscription has been initialized, errors may still occur server side. The subscription may be listened to in order to receive these events which are emitted as nosub events (the naming comes from Meteor which this publication system is based off of, see this documentation for more detail).

let helloSub = client.subscribe('hello');

helloSub.on('nosub', (err) => {
  console.log(`the subscription experienced an error: ${err.message}`);
});

Querying collections

The publication client also manages all collections created by the subscribed publications. Retrieving a collection is as simple as:

var collection = client.getCollection('baz');

We can then find documents of interest and listen for changes that we're interested in. To find documents and retrieve them:

var docs = client.getCollection('baz').find({
  _id: 'hello'
}).fetch();

Note that currently find only supports direct matching (as in the example above) and the $elemMatch operator for matchin objects inside of arrays.

To listen for changes that match a provided query:

client.getCollection('baz').find({
  _id: 'foo'
}).on('added', (id, fields) => {
  // `fields` contains all fields of the document excluding the `_id` field.
  console.log(`added a new document: ${Object.assign({}, {id}, fields)}`);
}).on('changed', (id, changes) => {
  // `changes` contains the changed fields with their new values.
  // If a field was removed from the document then it will be present in `changes`
  // with a value of `undefined`.
  console.log(`document with id ${id} has changes: ${changes}`);
}).on('removed', (id) => {
  console.log(`removed document with id: ${id}`);
});

Note that the handlers for these events are the same as those for Meteor's Mongo.Cursor.observeChanges (specifically the added, changed and removed events).

Closing the connection

If for whatever need, you need to close the publication connection, simply use the stop() method. Note that once you do this you, you'll need to recreate an entirely new publication-client to reconnect.

client.stop();