forked from oakserver/oak
-
Notifications
You must be signed in to change notification settings - Fork 0
/
response.ts
88 lines (72 loc) · 2.28 KB
/
response.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
// Copyright 2018-2020 the oak authors. All rights reserved. MIT license.
import { contentType, Status } from "./deps.ts";
import { isHtml } from "./util.ts";
interface ServerResponse {
status?: number;
headers?: Headers;
body?: Uint8Array;
}
const BODY_TYPES = ["string", "number", "bigint", "boolean", "symbol"];
const encoder = new TextEncoder();
export class Response {
#writable = true;
#getBody = (): Uint8Array | undefined => {
const typeofBody = typeof this.body;
let result: Uint8Array | undefined;
this.#writable = false;
if (BODY_TYPES.includes(typeofBody)) {
const bodyText = String(this.body);
result = encoder.encode(bodyText);
this.type = this.type || (isHtml(bodyText) ? "html" : "text/plain");
} else if (this.body instanceof Uint8Array) {
result = this.body;
} else if (typeofBody === "object" && this.body !== null) {
result = encoder.encode(JSON.stringify(this.body));
this.type = this.type || "json";
}
return result;
};
#setContentType = (): void => {
if (this.type) {
const contentTypeString = contentType(this.type);
if (contentTypeString && !this.headers.has("Content-Type")) {
this.headers.append("Content-Type", contentTypeString);
}
}
};
/** The body of the response */
body?: any;
/** Headers that will be returned in the response */
headers = new Headers();
/** The HTTP status of the response */
status?: Status;
/** The media type, or extension of the response */
type?: string;
get writable(): boolean {
return this.#writable;
}
/** Take this response and convert it to the response used by the Deno net
* server. */
toServerResponse(): ServerResponse {
// Process the body
const body = this.#getBody();
// If there is a response type, set the content type header
this.#setContentType();
// If there is no body and no content type and no set length, then set the
// content length to 0
if (
!(
body ||
this.headers.has("Content-Type") ||
this.headers.has("Content-Length")
)
) {
this.headers.append("Content-Length", "0");
}
return {
status: this.status || (body ? Status.OK : Status.NotFound),
body,
headers: this.headers,
};
}
}