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

socket.io-mongodb

v1.1.1

Published

A MongoDB Adapter for socket.io

Downloads

48

Readme

socket.io-mongodb

A MongoDB Adapter for socket.io, based on socket.io-redis.

This adapter:

  • Implements the full socket.io-adapter, including rooms and room deletion
  • Supports SSL connections to the database
  • Leverages mubsub

How to use

var io = require('socket.io')(3000),
    mongoAdapter = require('socket.io-mongodb');

io.adapter(mongoAdapter('mongodb://localhost:27017/socket-io'));

By running socket.io with the socket.io-mongodb adapter you can run multiple socket.io instances in different processes or servers that can all broadcast and emit events to and from each other.

If you need to emit events to socket.io instances from a non-socket.io process, you should use socket.io-emitter.

API

adapter(uri[, opts])

The first argument, uri, expects a MongoDB connection string (i.e. mongodb://localhost:27017/socket-io). The options argument is explained below.

var io = require('socket.io')(3000),
    mongoAdapter = require('socket.io-mongodb'),
    adapter;

adapter = mongoAdapter('mongodb://localhost:27017/socket-io', {
    prefix: 'myprefix',
    collectionName: 'mypubsub'
});

io.adapter(adapter);

adapter(opts)

The options described here can be passed in as the first argument, or as the second argument, when the first argument is your MongoDB connection string.

  • uri (required string or object): a MongoDB connection string, or a URI object that can be parsed by mongodb-uri
  • prefix (optional string): a prefix to be used when publishing events (default is socket-io)
  • collectionName (optional string): the name of the MongoDB collection that mubsub should create/use (default is pubsub). This is ignored if the mongoClient or pubsubClient properties are defined.
  • mongoClient (optional instance of MongoDB node driver): the MongoDB driver to use. This is ignored if the pubsubClient is defined. @alsoSee Existing database connection
  • pubsubClient (optional instance of mubsub): the mubsub client to use. This can be replaced by another library that implements the channel, channel.subscribe, and channel.publish interfaces. @alsoSee Custom client
  • channel (optional mubsub channel): the mubsub channel to use. This is only respected if the pubsubClient is also defined. @alsoSee Custom client
  • messageEncoder (optional object): an object with encode and decode functions, to be used when encoding/decoding pubsub messages. The default uses JSON.stringify and JSON.parse to encode and decode, respectively. @alsoSee: Overriding the messageEncoder
var io = require('socket.io')(3000),
    mongoAdapter = require('socket.io-mongodb'),
    adapter;
    //fs = require('fs'),
    //sslCA = [fs.readFileSync(__dirname + '/mySSLCA.pem')]; // you may want to switch this to `readFile` so as not to block - it's just here for example

adapter = mongoAdapter({
    "uri": {
        "hosts": [
            {
                "host": "db01.mysite.com",
                "port": 27017
            },
            {
                "host": "db02.mysite.com",
                "port": 27017
            }
        ],
        "username": "admin",
        "password": "password",
        "database": "socket-io",
        "options": {
            "authSource": "admin",
            "replicaSet": "myreplset",
            "ssl": true
        }
    },
    "server": {
        //"sslCA": sslCA
        "sslValidate": false
    },
    "replSet": {
        //"sslCA": sslCA
        "sslValidate": false
    }
    "prefix": 'myprefix',
    "collectionName": 'mypubsub'
});

io.adapter(adapter);

The options that are described here are passed through to mubsub, which in turn passes them to the native MongoDB driver. So you can include options that are relevant to those libraries. Also, if you pass an object in as the uri property, it is processed by mongodb-uri.

Client error handling

This adapter exposes the pubsubClient property (mubsub), as well as the channel that was created. You can bind to events on each of these resources:

var io = require('socket.io')(3000),
    mongoAdapter = require('socket.io-mongodb'),
    adapter = mongoAdapter('mongodb://localhost:27017/socket-io');

io.adapter(adapter);
adapter.pubsubClient.on('error', console.error);
adapter.channel.on('error', console.error);

Custom client

You can inject your own pubsub client (i.e. if you already have an instance of mubsub you wish to use), using the pubsubClient property of the options.

var io = require('socket.io')(3000),
    mubsub = require('mubsub'),
    mongoAdapter = require('socket.io-mongodb'),
    client;

client = mubsub('mongodb://localhost:27017/io-example');
channel = client.channel('test');   // the channel is optional

io.adapter(mongoAdapter({
    pubsubClient: mubsub,
    channel: channel                // optional
}));

Existing database connection

You can inject an existing database connection, if you are not injecting the pubsubClient.

var io = require('socket.io')(3000),
    MongoClient = require('mongodb').MongoClient,
    mongoAdapter = require('socket.io-mongodb'),
    client;

MongoClient.connect('mongodb://localhost:27017/io-example', function(err, db) {
    io.adapter(mongoAdapter({
        mongoClient: db
    }));
});

The MongoClient is exposed as db on the adapter, so you can leverage it if you need to: myAdapter.db

Overriding the messageEncoder

If you don't want or need to be able to read the message data in the database, you may benefit from overriding the messageEncoder. The following example uses msgpack-js to encode/decode the message data.

var io = require('socket.io')(3000),
    mongoAdapter = require('socket.io-mongodb'),
    msgpack = require('msgpack-js');

io.adapter(mongoAdapter({
    uri: 'mongodb://localhost:27017/socket-io',
    messageEncoder: {
        encode: function (data) {
            return msgpack.encode(data);
        },
        decode: function (data) {
            return msgpack.decode(data.buffer);
        }
    }
}));

Protocol

The socket.io-mongodb adapter broadcasts and receives messages on particularly named channels. For global broadcasts the channel name is:

prefix + '#' + namespace + '#'

In broadcasting to a single room the channel name is:

prefix + '#' + namespace + '#' + room + '#'
  • prefix: a prefix to be used when publishing events (default is socket-io). You can change this by setting the prefix value in the constructor options
  • namespace: see https://github.com/socketio/socket.io#namespace.
  • room : used if targeting a specific room.

License

MIT