summaryrefslogtreecommitdiff
path: root/frontend/src/utils/websocket.js
blob: b01531cf1a9c04b25f09c04670f683fbb500bcf8 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
// @flow
import SockJS from 'sockjs-client';
import Stomp from 'webstomp-client';
import { eventChannel } from 'redux-saga';

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

export type FrameType = {
  body: string,
  command: string,
  header: {
    'heart-beat': number,
    'user-name': string,
    version: string
  }
};
export type SocketType = {
  connect: (headers: Object, onSucces: (frame: FrameType) => void, onReject: (error: any) => void) => void,
  subscribe: (path: string, callback: (event: any) => void) => Object
};
export type SocketSubscriptionType = {
  id: string,
  unsubscribe: () => void
};
export type SocketEventType = {
  body: string
};
export type SocketObjectType = {
  frame: FrameType,
  socket: SocketType
};

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

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