connect method

Stream<SseEvent> connect(
  1. Uri uri, {
  2. String method = 'GET',
  3. Map<String, String>? headers,
  4. Object? body,
})

Connects to the SSE endpoint and yields SseEvents.

uri The URI of the SSE endpoint. method The HTTP method to use. headers The headers to send with the request. body The body to send with the request.

Returns a stream of SseEvent objects. Throws an Exception if the request fails. Throws a http.ClientException if the response is not successful.

Implementation

Stream<SseEvent> connect(
  Uri uri, {
  String method = 'GET',
  Map<String, String>? headers,
  Object? body,
}) async* {
  try {
    final request = http.Request(method, uri);

    if (headers != null) {
      request.headers.addAll(headers);
    }

    if (body != null && _methodSupportsBody(method)) {
      if (body is Map || body is List) {
        request.headers['Content-Type'] = _MimeType.json.value;
        request.body = jsonEncode(body);
      } else {
        request.body = '$body';
        request.headers['Content-Type'] = _MimeType.text.value;
      }
    }

    final response = await _client.send(request);

    if (!_isSuccess(response.statusCode)) {
      throw http.ClientException(
        'Failed to connect: ${response.statusCode} ${response.reasonPhrase}',
        uri,
      );
    }

    final stream = response.stream
        .transform(utf8.decoder)
        .transform(const LineSplitter())
        .transform(const SseEventTransformer());

    yield* stream;
  } catch (e) {
    throw Exception('Failed to create request: $e');
  }
}