Skip to content

Commit c19e9e1

Browse files
committed
feat: add StreamedResponse for streaming response bodies
Adds a `StreamedResponse` class extending `Response`, enabling chunked transfer encoding for streaming response bodies via readable streams. Automatically sets `transfer-encoding: chunked` if not specified. Closes #9
1 parent 7b671f5 commit c19e9e1

File tree

1 file changed

+28
-0
lines changed

1 file changed

+28
-0
lines changed

src/response/StreamedResponse.ts

Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
1+
import http from "node:http";
2+
import stream from "node:stream/promises";
3+
import {Request} from "../Request.js";
4+
import {Response} from "./Response.js";
5+
6+
/**
7+
* A response that streams data from a readable stream.
8+
*/
9+
export class StreamedResponse<A> extends Response<A> {
10+
private readonly stream: NodeJS.ReadableStream;
11+
12+
/**
13+
* Construct a StreamedResponse.
14+
* @param stream The readable stream to send in the response body.
15+
* @param [statusCode=200] The HTTP response status code to send.
16+
* @param [headers] The HTTP response headers to send.
17+
*/
18+
public constructor(stream: NodeJS.ReadableStream, statusCode = 200, headers?: HeadersInit) {
19+
super(statusCode, headers);
20+
this.stream = stream;
21+
if (!this.headers.has("transfer-encoding")) this.headers.set("transfer-encoding", "chunked");
22+
}
23+
24+
protected override async send(res: http.ServerResponse, req?: Request<A>): Promise<void> {
25+
this.writeHead(res, req);
26+
await stream.pipeline(this.stream, res);
27+
}
28+
}

0 commit comments

Comments
 (0)