Server constructor

Server(
  1. RemoteClient client, {
  2. Duration? keepAliveInterval,
})

Implementation

Server(this.client, {this.keepAliveInterval}) {
  _sub = client.stream.listen(
    (msg) async {
      if ((msg.type == OperationMessage.gqlConnectionInit) && !_init) {
        try {
          Map? connectionParams;
          if (msg.payload is Map) {
            connectionParams = msg.payload as Map?;
          } else if (msg.payload != null) {
            throw FormatException(
              '${msg.type} payload must be a map (object).',
            );
          }

          var connect = await onConnect(client, connectionParams);
          // The connection may have ended while onConnect ran.
          if (_ended) return;
          if (!connect) throw false;
          _init = true;
          client.sink.add(
            OperationMessage(OperationMessage.gqlConnectionAck),
          );

          if (keepAliveInterval != null) {
            client.sink.add(
              OperationMessage(OperationMessage.gqlConnectionKeepAlive),
            );
            _timer ??= Timer.periodic(keepAliveInterval!, (timer) {
              client.sink.add(
                OperationMessage(OperationMessage.gqlConnectionKeepAlive),
              );
            });
          }
        } catch (e) {
          if (e == false) {
            _reportError('The connection was rejected.');
          } else {
            _reportError(e.toString());
          }
        }
      } else if (_init) {
        if (msg.type == OperationMessage.gqlStart) {
          await _start(msg);
        } else if (msg.type == OperationMessage.gqlStop) {
          if (msg.id case var id?) _stop(id);
        } else if (msg.type == OperationMessage.gqlConnectionTerminate) {
          await _end();
          client.close();
        }
      }
    },
    // A connection that failed is closed, rather than kept open unanswered.
    onError: (_) async {
      await _end();
      client.close();
    },
    onDone: _end,
  );
}