Skip to content

Commit 504156c

Browse files
committed
make buffer response contents available at initialisation time
1 parent 8d58621 commit 504156c

File tree

2 files changed

+21
-17
lines changed

2 files changed

+21
-17
lines changed

src/response/BufferResponse.ts

Lines changed: 12 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -9,19 +9,23 @@ export abstract class BufferResponse<A> extends Response<A> {
99
/**
1010
* Fetch the buffer to send in the response body.
1111
*/
12-
protected abstract readBuffer(): Uint8Array | Promise<Uint8Array>;
12+
protected abstract readonly buffer: Uint8Array;
1313

14-
protected override async send(res: http.ServerResponse, req?: Request<A>): Promise<void> {
15-
const buffer = await this.readBuffer();
14+
public override allHeaders(res: http.ServerResponse, req?: Request<A>) {
15+
const headers = super.allHeaders(res, req);
1616
if (req !== undefined) {
1717
if (res.chunkedEncoding) {
18-
if (!this.headers.has("transfer-encoding"))
19-
this.headers.set("transfer-encoding", "chunked");
18+
if (!headers.has("transfer-encoding"))
19+
headers.set("transfer-encoding", "chunked");
2020
}
21-
else if (!this.headers.has("content-length"))
22-
this.headers.set("content-length", buffer.byteLength.toString());
21+
else if (!headers.has("content-length"))
22+
headers.set("content-length", this.buffer.byteLength.toString());
2323
}
24+
return headers;
25+
}
26+
27+
protected override async send(res: http.ServerResponse, req?: Request<A>): Promise<void> {
2428
this.writeHead(res, req);
25-
res.end(buffer);
29+
res.end(this.buffer);
2630
}
2731
}

src/response/TextResponse.ts

Lines changed: 9 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -1,13 +1,12 @@
1+
import http from "node:http";
2+
import {Request} from "../Request.js";
13
import {BufferResponse} from "./BufferResponse.js";
24

35
/**
46
* An HTTP response with a plain text body.
57
*/
68
export class TextResponse<A> extends BufferResponse<A> {
7-
/**
8-
* The plain text body of the response.
9-
*/
10-
protected readonly text: string;
9+
protected override readonly buffer: Uint8Array;
1110
private readonly encoder = new TextEncoder();
1211

1312
/**
@@ -18,12 +17,13 @@ export class TextResponse<A> extends BufferResponse<A> {
1817
*/
1918
public constructor(text: string, statusCode = 200, headers?: HeadersInit) {
2019
super(statusCode, headers);
21-
this.text = text;
22-
if (!this.headers.has("content-type"))
23-
this.headers.set("content-type", "text/plain");
20+
this.buffer = this.encoder.encode(text);
2421
}
2522

26-
public override readBuffer() {
27-
return this.encoder.encode(this.text);
23+
public override allHeaders(res: http.ServerResponse, req?: Request<A>): Headers {
24+
const headers = super.allHeaders(res, req);
25+
if (!headers.has("content-type"))
26+
headers.set("content-type", "text/plain");
27+
return headers;
2828
}
2929
}

0 commit comments

Comments
 (0)