about summary refs log tree commit diff
path: root/app/assets/javascripts/components/stream.jsx
blob: 08da7160718045ae3d9e54853ae89b5b919ea22d (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
import WebSocketClient from 'websocket.js';

const createWebSocketURL = (url) => {
  const a = document.createElement('a');

  a.href     = url;
  a.href     = a.href;
  a.protocol = a.protocol.replace('http', 'ws');

  return a.href;
};

export default function getStream(streamingAPIBaseURL, accessToken, stream, { connected, received, disconnected, reconnected }) {
  const ws = new WebSocketClient(`${createWebSocketURL(streamingAPIBaseURL)}/api/v1/streaming/?access_token=${accessToken}&stream=${stream}`);

  ws.onopen      = connected;
  ws.onmessage   = e => received(JSON.parse(e.data));
  ws.onclose     = disconnected;
  ws.onreconnect = reconnected;

  return ws;
};