Skip to content

Commit

Permalink
Add Server-Sent Events (SSE) response (vania-dart#89)
Browse files Browse the repository at this point in the history
  • Loading branch information
javad-zobeidi committed Jul 3, 2024
1 parent a95e27c commit 4448175
Showing 1 changed file with 35 additions and 0 deletions.
35 changes: 35 additions & 0 deletions lib/src/http/response/response.dart
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ enum ResponseType {
json,
none,
html,
sse,
streamFile,
download,
}
Expand All @@ -29,6 +30,25 @@ class Response {
this.headers = const {},
});

@protected
Future<void> sseHandler(HttpResponse res) async {
res.headers.contentType = ContentType.parse('text/event-stream');
res.headers.add(HttpHeaders.cacheControlHeader, 'no-cache');
res.headers.add(HttpHeaders.connectionHeader, 'keep-alive');
res.headers.add(HttpHeaders.transferEncodingHeader, 'chunked');

void writeSSE(String data) {
res.add(utf8.encode('data: $data\n\n'));
}

await for (var event in data) {
writeSSE(jsonEncode(event));
await res.flush();
}

await res.close();
}

void makeResponse(HttpResponse res) async {
res.statusCode = httpStatusCode;
if (headers.isNotEmpty) {
Expand All @@ -51,6 +71,9 @@ class Response {
res.write(data);
await res.close();
break;
case ResponseType.sse:
await sseHandler(res);
break;
case ResponseType.streamFile:
StreamFile? stream = StreamFile(
fileName: data['fileName'],
Expand Down Expand Up @@ -134,6 +157,18 @@ class Response {
headers: headers,
);

static sse(
Stream<dynamic> eventStream, {
int statusCode = HttpStatus.ok,
Map<String, String> headers = const {},
}) =>
Response(
data: eventStream,
responseType: ResponseType.sse,
httpStatusCode: statusCode,
headers: headers,
);

static download(
String fileName,
Uint8List bytes, {
Expand Down

0 comments on commit 4448175

Please sign in to comment.