{"size": 1543, "ext": "js", "max_stars_repo_path": "client/src/store/sagas/sockets/io.js", "max_stars_repo_name": "FMI-Projects/jitter", "max_stars_repo_stars_event_min_datetime": "2020-07-27T20:00:48.000Z", "max_stars_repo_stars_event_max_datetime": "2020-07-27T20:00:48.000Z", "max_issues_repo_path": "client/src/store/sagas/sockets/io.js", "max_issues_repo_name": "FMI-Projects/jitter", "max_issues_repo_issues_event_min_datetime": "2020-07-16T03:56:31.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-17T15:50:58.000Z", "max_forks_repo_path": "client/src/store/sagas/sockets/io.js", "max_forks_repo_name": "FMI-Projects/jitter", "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null}
{"max_stars_count": 1, "max_issues_count": 11, "max_forks_count": null, "avg_line_length": 24.109375, "max_line_length": 85, "alphanum_fraction": 0.6098509397}
import io from "socket.io-client";
import wildcard from "socketio-wildcard";
import { eventChannel } from "redux-saga";
import { put, call, take, fork, cancel } from "redux-saga/effects";

import sagas from "./sagas";
import payloadToNormalisedImmutable from "./utilities/payloadToNormalisedImmutable";

const patch = wildcard(io.Manager);
const baseUrl = "http://localhost:8000";

let socket;
let socketSagas;
let socketChannel;

export function* openSocket(token) {
  socketChannel = yield call(initializeSocket, token);
  socketSagas = yield fork(sagas, socket);

  while (true) {
    const action = yield take(socketChannel);
    yield put(action);
  }
}

export function* closeSocket() {
  if (socketChannel) {
    yield call(socketChannel.close);
    socketChannel = null;
  }

  if (socketSagas) {
    yield cancel(socketSagas);
    socketSagas = null;
  }

  socket = null;
}

function initializeSocket(token) {
  return eventChannel(emitter => {
    socket = io(baseUrl);
    patch(socket);

    socket.on("connect", function() {
      socket.emit("authentication", { token });
      socket.on("authenticated", () => {
        socket.on("*", params => {
          const actionType = params.data[0];
          const payload = payloadToNormalisedImmutable(
            actionType,
            params.data[1]
          );
          return emitter({ type: actionType, ...payload });
        });
      });
    });

    return () => {
      socket.disconnect();
    };
  });
}
