-
Notifications
You must be signed in to change notification settings - Fork 17
/
response.ts
104 lines (87 loc) · 2.54 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
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
import { ReadCloser } from "./io.ts";
const encoder = new TextEncoder();
// HeaderMap is a type of response headers.
type HeaderMap =
| Headers
| {
[key: string]: any;
};
// ResponseBody is a type of response body.
type ResponseBody = string | ReadCloser | Deno.Reader;
/*
* Types of Response
*/
// StatusHeadersBodyResponse is a response with status code, headers, body.
type StatusHeadersBodyResponse = [number, HeaderMap, ResponseBody];
// StatusBodyResponse is a response with status code, body.
type StatusBodyResponse = [number, ResponseBody];
// Response is a type of response.
export type Response =
| StatusHeadersBodyResponse
| StatusBodyResponse
| number // HTTP status code only
| ResponseBody; // Response body only
// Response interface
interface HTTPResponse {
status?: number;
headers?: Headers;
body?: Uint8Array | ReadCloser | Deno.Reader;
}
export function processResponse(res: Response): HTTPResponse {
let status = 200;
let headerMap: HeaderMap = {};
let rawBody: ResponseBody = "";
if (isStatusHeadersBodyResponse(res)) {
[status, headerMap, rawBody] = res;
} else if (isStatusBodyResponse(res)) {
[status, rawBody] = res;
} else if (isNumberResponse(res)) {
status = res;
} else if (isReadCloserResponse(res)) {
rawBody = res;
} else if (isReaderResponse(res)) {
rawBody = res;
} else if (isStringResponse(res)) {
rawBody = res;
}
let body: Uint8Array | ReadCloser | Deno.Reader;
if (typeof rawBody === "string") {
body = encoder.encode(rawBody);
} else {
body = rawBody;
}
const headers = new Headers(headerMap);
return {
status,
body,
headers,
};
}
function isStatusHeadersBodyResponse(
res: Response,
): res is StatusHeadersBodyResponse {
const r = res as StatusHeadersBodyResponse;
return Array.isArray(r) && r.length === 3;
}
function isStatusBodyResponse(res: Response): res is StatusBodyResponse {
const r = res as StatusBodyResponse;
return Array.isArray(r) && r.length === 2;
}
function isNumberResponse(res: Response): res is number {
return typeof res === "number";
}
function isReadCloserResponse(res: Response): res is ReadCloser {
const r = res as ReadCloser;
return (
typeof r === "object" &&
typeof r.read === "function" &&
typeof r.close === "function"
);
}
function isReaderResponse(res: Response): res is Deno.Reader {
const r = res as Deno.Reader;
return typeof r === "object" && typeof r.read === "function";
}
function isStringResponse(res: Response): res is string {
return typeof res === "string";
}