Sawtaytoes
12/12/2019 - 6:56 AM

WebSocket connection epic

const connectToServerEpic = (
  action$,
) => (
  action$
  .pipe(
    ofType(CONNECT_TO_SERVER),
    switchMap(({
      hostname,
      port,
      protocol,
      protocolVersion,
      reconnectionTimeout,
    }) => (
      action$
      .pipe(
        ofType(RECONNECT_TO_SERVER),
        takeUntil(
          action$
          .pipe(
            ofType(DISCONNECT_FROM_SERVER),
          )
        ),
        startWith(null),
        map(() => (
          webSocket({
            protocol: protocolVersion,
            url: (
              protocol
              .concat('://')
              .concat(hostname)
              .concat(':')
              .concat(port)
            ),
            WebSocketCtor: WebSocket,
          })
        )),
        switchMap((
          webSocketConnection$,
        ) => (
          webSocketConnection$
          .pipe(
            takeUntil(
              action$
              .pipe(
                ofType(
                  RECONNECT_TO_SERVER,
                  DISCONNECT_FROM_SERVER,
                ),
              )
            ),
            catchError(() => (
              timer(
                reconnectionTimeout,
              )
              .pipe(
                takeUntil(
                  action$
                  .pipe(
                    ofType(
                      RECONNECT_TO_SERVER,
                      DISCONNECT_FROM_SERVER,
                    ),
                  )
                ),
                mapTo(reconnectToServer()),
              )
            )),
            map(receivedWebSocketMessage),
            startWith(
              connectionReady(
                webSocketConnection$,
              )
            ),
          )),
        )),
      )
    )),
  )
)