You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

77 lines
1.8 KiB

  1. import WebSocketClient from 'websocket.js';
  2. export function connectStream(path, pollingRefresh = null, callbacks = () => ({ onDisconnect() {}, onReceive() {} })) {
  3. return (dispatch, getState) => {
  4. const streamingAPIBaseURL = getState().getIn(['meta', 'streaming_api_base_url']);
  5. const accessToken = getState().getIn(['meta', 'access_token']);
  6. const { onDisconnect, onReceive } = callbacks(dispatch, getState);
  7. let polling = null;
  8. const setupPolling = () => {
  9. polling = setInterval(() => {
  10. pollingRefresh(dispatch);
  11. }, 20000);
  12. };
  13. const clearPolling = () => {
  14. if (polling) {
  15. clearInterval(polling);
  16. polling = null;
  17. }
  18. };
  19. const subscription = getStream(streamingAPIBaseURL, accessToken, path, {
  20. connected () {
  21. if (pollingRefresh) {
  22. clearPolling();
  23. }
  24. },
  25. disconnected () {
  26. if (pollingRefresh) {
  27. setupPolling();
  28. }
  29. onDisconnect();
  30. },
  31. received (data) {
  32. onReceive(data);
  33. },
  34. reconnected () {
  35. if (pollingRefresh) {
  36. clearPolling();
  37. pollingRefresh(dispatch);
  38. }
  39. },
  40. });
  41. const disconnect = () => {
  42. if (subscription) {
  43. subscription.close();
  44. }
  45. clearPolling();
  46. };
  47. return disconnect;
  48. };
  49. }
  50. export default function getStream(streamingAPIBaseURL, accessToken, stream, { connected, received, disconnected, reconnected }) {
  51. const params = [ `stream=${stream}` ];
  52. if (accessToken !== null) {
  53. params.push(`access_token=${accessToken}`);
  54. }
  55. const ws = new WebSocketClient(`${streamingAPIBaseURL}/api/v1/streaming/?${params.join('&')}`);
  56. ws.onopen = connected;
  57. ws.onmessage = e => received(JSON.parse(e.data));
  58. ws.onclose = disconnected;
  59. ws.onreconnect = reconnected;
  60. return ws;
  61. };