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

bsock-middleware

v1.1.5

Published

redux middleware for websocket actions using the bsock client

Downloads

1

Readme

bsock-middleware

This package is a redux middleware implementation for websocket actions using the bsock client.

QUICK START

npm install --save bsock-middleware

import { createStore, applyMiddleware } from 'redux';
import thunkMiddleware from 'redux-thunk';
import bsockMiddleware from 'bsock-middleware';

import rootReducer from './reducers';

export default function configureStore(initialState) {
  return createStore(rootReducer, initialState,
    applyMiddleware(thunkMiddleware, bsockMiddleware)
  )
}

What is bsock?

bsock is a minimal websocket-only implementation of the socket.io protocol, complete with ES6/ES7 features. It is extremely performant and lightweight. It is also compatible with the socket.io api so this can be used to communicate with a socket.io server if necessary. More information on bsock, see the official repo on GitHub

Redux Middleware and Websockets

This redux middleware implementation is based off the following resources and examples:

To get a detailed overview of how middlewares work in redux, check out the official docs. The basic idea is that through some JavaScript currying magic and leveraging the predictablity of state changes you can intercept actions to operate on from middleware (and pass along to subsequent middleware if necessary). From the docs:

One of the benefits of Redux is that it makes state changes predictable and transparent. Every time an action is dispatched, the new state is computed and saved. The state cannot change by itself, it can only change as a consequence of a specific action

[Middleware] provides a third-party extension point between dispatching an action, and the moment it reaches the reducer. People use Redux middleware for logging, crash reporting, talking to an asynchronous API, routing, and more.

Middleware is particularly useful when dealing with networking and async operations that operate on the store. For situations when we want websocket interactions to update the state of the store, say we receive a message that should update the state or want to send a message and change the state upon acknowledgement from the server, we have middleware.

The important things that a piece of middleware gets access to are the actions and the store. This means we can do things like dispatch or getState from our middleware, or check what a action.type is that has been dispatched.

Usage

bsock-middleware checks for a few things when it intercepts actions. If an action does not have a bsock property at all, it just passes the action on to the next middleware in the chain via return next(action).

Action Types

If it does have a bsock property then these are the action types it reacts to:

  • CONNECT_SOCKET
  • DISCONNECT_SOCKET
  • EMIT_SOCKET

(Notice there is nothing for listeners. We'll get to that next).

Options for each are sent as properties in the bsock property on the action.

CONNECT_SOCKET accepts port, host, ssl, and protocols

DISCONNECT_SOCKET takes no properties

EMIT_SOCKET takes type, message, and an optional acknowledge function. If there is an acknowledge function passed, bsock will use the call method instead of fire and wait to receive an acknowledgement which will then be passed to the passed acknowledge function. This should be an action creator as it gets passed to the store's dispatch function.

Options and Listeners

bsockMiddleware returns a function. To add the middleware you call it and can optionally pass in an options object which currently takes only two properties: debug (bool) and listeners. debug is self-explanatory (true will log status messages to your console). listeners is an array of listener objects with properties event and actionType (both strings) and an optional ack property.

When you connect a socket, any listeners passed in the options are added to the socket. What happens is that when an event is "heard", the payload is received and then passed to an action creator with type actionType and payload payload which is then dispatched. If there is an ack property, then the hook method is used which returns an acknowledgement message of Buffer.from(ack) after dispatching the action creator.

Simple Example

First install the package with npm:

npm install --save bsock-middleware

Middleware

/* store/index.js */

import { combineReducers, createStore, applyMiddleware } from 'redux';
import thunkMiddleware from 'redux-thunk';
import bsockMiddleware from 'bsock-middleware';

import * as reducers from './reducers';

const listeners = [
  {
    event: 'foo bar',
    actionType: 'FOO_BAR_RECEIVED'
  }
];

const options = { debug: true, listeners };

const rootReducer = combineReducers(reducers);
const middleware = [thunkMiddleware, bsockMiddleware(options)]

const store = createStore(rootReducer, applyMiddleware(...middleware));

export default store;

Action Creators

/* store/actions/socketActions.js */

export function connectSocket() {
  return {
    type: 'CONNECT_SOCKET',
    bsock: {
      host: 'localhost',
      port: 5000
    }
  };
};

export function emitFizz() {
  return {
    type: 'EMIT_SOCKET',
    bsock: {
      type: 'fizz',
      message: Buffer.from('buzz'),
      acknowledge: acknowledgeFizzBuzz
    }
  }
}

export function acknowledgeFizzBuzz(ack) {
  return {
    type: 'ACKNOWLEDGE_FIZZ_BUZZ',
    payload: ack
  }
}

Reducer

/* store/reducers/index.js */

export const fooState(state = {}, action){
  let newState = { ...state };
  switch (action.type) {
    case 'FOO_BAR_RECEIVED': {
      newState.fooBar = action.payload
      return newState;
    }
    default:
      return state;
  }
}

Then at the entry point of your app simply dispatch connectSocket(). After that, you can start listening for foo bar via the FOO_BAR_RECEIVED action type, emitting by dispatching emitFizz, and even catch erros with SOCKET_ERROR (dispatched by the middleware).

Contribution and License Agreement

If you contribute code to this project, you are implicitly allowing your code to be distributed under the MIT license. You are also implicitly verifying that all code is your original work. </legalese>

License

  • Copyright (c) 2017, Buck Perley (MIT License).