summaryrefslogtreecommitdiff
path: root/frontend/src/api/websocket.js
blob: 8a893a871330d6fedbcce5b6370f063ca83412a1 (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
49
50
51
52
53
54
55
56
57
58
59
60
61
// @flow
import SockJS from 'sockjs-client';
import Stomp from 'webstomp-client';
import type { Client, Frame, Options, Subscription } from 'webstomp-client';

const DEFAULT_DEBUG_OPTIONS = {
  debug: process.env.NODE_ENV !== 'production',
};

export type Callback<T> = (value?: T) => void;
export type UnsubscribeFn = () => void;
export type SubscribeFn<T> = (callback: Callback<T>) => UnsubscribeFn;

export class JsonStompClient {
  client: Client;

  constructor(client: Client) {
    this.client = client;
  }

  connect(headers: Object = {}): Promise<Frame> {
    return new Promise((resolve, reject) => {
      this.client.connect(headers, resolve, reject);
    });
  }

  subscribe<T>(path: string, callback: Callback<T>): UnsubscribeFn {
    const socketSubscription: Subscription = this.client.subscribe(path, (frame: Frame) => {
      // not all frames have a JSON body
      const value: T = frame && JsonStompClient.parseBody(frame);
      callback(value);
    });
    return () => socketSubscription.unsubscribe();
  }

  static parseBody<T>(frame: Frame): T | void {
    try {
      return frame.body && JSON.parse(frame.body);
    } catch (jsonParseError) {
      throw new Error('Cannot parse websocket message as JSON: ' + jsonParseError.message);
    }
  }

  subscriber<T>(path: string): SubscribeFn<T> {
    return (callback: Callback<T>) => this.subscribe(path, callback);
  }

  send(url: string, body?: Object) {
    const strBody = body ? JSON.stringify(body) : '';
    this.client.send(url, strBody);
  }
}

function createStompClient(url: string, options: Options = {}): Client {
  const optionsWithDebug = Object.assign({}, DEFAULT_DEBUG_OPTIONS, options);
  return Stomp.over(new SockJS(url), optionsWithDebug);
}

export function createJsonStompClient(url: string, options: Options = {}): JsonStompClient {
  return new JsonStompClient(createStompClient(url, options));
}
bgstack15