summaryrefslogtreecommitdiff
path: root/frontend/src/utils/websocket.js
blob: 2751b16cfba94a778426587e9558d520a8e8386c (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
// @flow
import SockJS from 'sockjs-client';
import Stomp from 'webstomp-client';
import { eventChannel } from 'redux-saga';

const wsURL = '/seven-wonders-websocket';

export const createWsConnection = (headers: Object = {}) =>
  new Promise((resolve, reject) => {
    let socket = Stomp.over(new SockJS(wsURL), {
      debug: process.env.NODE_ENV !== 'production',
    });
    socket.connect(headers, frame => resolve({ frame, socket }), reject);
  });

export const createSubscriptionChannel = (socket: any, path: string) => {
  return eventChannel(emitter => {
    const socketSubscription = socket.subscribe(path, event => {
      emitter(JSON.parse(event.body));
    });
    return () => socketSubscription.unsubscribe();
  });
};
bgstack15