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

redux-websocket-bridge

v0.3.0-0

Published

WebSocket messages to Redux action bridge

Downloads

1,343

Readme

Bridge WebSocket messages and Redux actions

npm version Build Status

Inspired by redux-websocket.

This bridge middleware will:

  • Dispatch WebSocket messages into Redux store
  • Lift Redux actions to WebSocket

Introduction

WebSocket provides a full duplex connection. On top of request-response model, the server can watch-and-push to the browser continuously. But comparing coding effort between REST and WebSocket, fetching data using REST is much simpler.

We want to reduce the effort to consume APIs exposed thru WebSocket.

By combining WebSocket and Flux architecture (Redux), we found that the coding effort can be dramatically lowered to a level comparable to traditional REST APIs.

Thus, we made Redux WebSocket bridge. It promotes WebSocket messages to a first-class citizen in Flux architecture, enabling front end developers with less knowledge on WebSocket to work with new collaborative and reactive services.

How to use

Store: adding middleware

import { applyMiddleware, createStore } from 'redux';
import ReduxWebSocketBridge from 'redux-websocket-bridge';

const createStoreWithMiddleware = applyMiddleware(
  ReduxWebSocketBridge('ws://localhost:4000/')
)(createStore);

export default createStoreWithMiddleware(...);

Tips: you can use namespace to add multiple ReduxWebSocketBridge

Reducer: handling incoming messages

When you receive any WebSocket messages that resembles a Flux Standard Action (FSA) in JSON, it will automatically parsed and dispatched to the store. We call this "unfold".

Server code

When the server send a JSON message that looks like a FSA, it will be automatically unfolded and dispatch to the store.

app.on('connection', socket => {
  socket.write(JSON.stringify({
    type: 'SERVER/GREETING',
    payload: { version: '1.0.0' }
  }));
});

Client code

function reducer(state = {}, action) {
  switch (action.type) {
  case 'SERVER/GREETING':
    // action.meta.webSocket reference to the WebSocket object
    return { ...state, ...action.payload, connected: true };

  default: break;
  }
}

Handling WebSocket events

For WebSocket events, they will be dispatched thru @@websocket/*.

import { OPEN, CLOSE, MESSAGE } from 'redux-websocket-bridge';

function serverConnectivity(state = {}, action) {
  switch (action.type) {
  case `@@websocket/${ OPEN }`:
    state = { ...state, connected: true };
    break;

  case `@@websocket/${ CLOSE }`:
    state = { ...state, connected: false };
    break;

  case `@@websocket/${ MESSAGE }`:
    // Process the raw message here, either string, ArrayBuffer, or Blob
    break;

  default: break;
  }

  return state;
}

Action: sending WebSocket messages

There are two ways to send WebSocket messages:

Sending raw WebSocket message

Payload will be send as-is without modifications. Depends on your WebSocket implementation, you may also send ArrayBuffer or Blob.

For example, to send a message thru Slack RTM API.

import { SEND } from 'redux-websocket-bridge';

function sendHelloWorld() {
  return {
    type: `@@websocket/${ SEND }`,
    payload: JSON.stringify({
      id: 1,
      type: 'message',
      channel: 'C024BE91L',
      text: 'Hello world'
    })
  };
}

Sending action as JSON

You can also opt-in to send any action dispatched to your store thru WebSocket. On the action object, set meta.send to true (or your namespace). When you dispatch the action, the bridge will also JSON.stringify and send a copy of the action to WebSocket.

this.props.dispatch({
  type: 'CLIENT/SIGN_IN',
  meta: { send: true } // or '@@websocket', or a WebSocket object,
  payload: { token: 'my very secret token' }
});

The action dispatched will be sent thru WebSocket similar to the following code. Note the meta.send property is stripped from the message and is not send across the wire.

ws.send(JSON.stringify({
  type: 'CLIENT/SIGN_IN',
  payload: { token: 'my very secret token' }
}));

Tips: you can also use the bridge on server-side to unfold messages back into a Redux store

What-if: if your action is not a FSA-compliant, we will still send it thru. This behavior may change in the future.

Advanced topics

Use SockJS or other implementations

The bridge supports any libraries that adheres to WebSocket standard, for example, SockJS, which provides fallback for browser/proxy that does not support WebSocket.

const createStoreWithMiddleware = applyMiddleware(
  WebSocketBridge(
    () => new SockJS('http://localhost:3000/ws/')
  )
)(createStore);

WebSocket APIs used by the bridge

Your WebSocket implementation will work on the bridge if they implemented the interface below:

interface WebSocket {
  onopen();
  onclose();
  onmessage(event: { data: string });
  send(data: string);
}

We currently do not process onerror, we might add it in near future.

Prefer ArrayBuffer

This feature is for browser only, it requires FileReader API

WebSocket support binary message. But receiving binary data means you might be receiving either ArrayBuffer or Blob, depends on your WebSocket implementation.

For your convenience, if you set binaryType to arraybuffer in options, we will convert all Blob to ArrayBuffer before dispatching it to Redux store. Because the conversion is an asynchronous operation (using FileReader), it is easier for the bridge to convert it for you.

Vice versa, if you set binaryType to blob, we will convert all ArrayBuffer into Blob.

Reconnection logic

For simplicity, the bridge does not have any reconnection mechanism. But it is easy to implement one, thanks to simple WebSocket API.

To implement your own reconnection logic, you can create a new WebSocket-alike. When disconnected, your implementation will recreate a new WebSocket object, which reconnect to your server. You will be managing the lifetime of WebSocket objects, event subscriptions, and resend backlog.

Although you are recommended to fully implement the WebSocket API, you can check out the subset required by the bridge.

Unfolding actions from multiple bridges

We support multiple bridges. In rare cases, you may want to tag unfolded actions from multiple bridges. You can write a middleware between bridges to tag actions.

const createStoreWithMiddleware = applyMiddleware(
  ReduxWebSocketBridge('ws://localhost:4000/'),
  store => next => action => {
    if (action === 'SERVER/GREETING') {
      action = { ...action, meta: { from: 'server1', ...action.meta } };
    }

    next(action);
  },
  ReduxWebSocketBridge('ws://localhost:4001/'),
  store => next => action => {
    if (action === 'SERVER/GREETING') {
      action = { ...action, meta: { from: 'server2', ...action.meta } };
    }

    next(action);
  },
)(createStore);

For clarity, we did not refactor the sample code.

In this example, we added two middleware to tag all SERVER/GREETING action, adding a meta.from property indicate where the action was from. Note the order of spread/rest property matters, we will not overriding meta.from if it was already defined.

You can refactor the code out and use RegExp for pattern-matching action types.

If this sample does not works for you, please do let us know.

Delayed connection setup

Some services requires calling their REST API before setting up a WebSocket connection, for example, Slack requires a handshake call rtm.connect to get the endpoint for their WebSocket RTM API.

You can create a WebSocket-alike to do the REST API handshake. Once your handshake is done, you can then establish the WebSocket connection. You will need to proxy events before the connection is made. But since the bridge prefer onopen than addEventListener, the effort is minimal.

Options

| Name | Description | Default | | - | - | - | | binaryType | Convert binary to "arraybuffer" or "blob" | null | | namespace | Action prefix for all system messages | "@@websocket/" | | unfold | Unfold messages as actions if they are JSON and look like a Flux Standard Action | true |

Contributions

Like us? Star us.

Something not right? File us an issue.