forked from tomphttp/bare-server-node
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathAbstractMessage.js
56 lines (48 loc) · 1.17 KB
/
AbstractMessage.js
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
import { OutgoingMessage } from 'node:http';
import Stream from 'node:stream';
import { Headers } from 'fetch-headers';
export { Headers };
// from 'fetch-headers';
export class Request {
constructor(body, method, path, headers) {
this.body = body;
this.method = method;
this.headers = new Headers(headers);
this.url = new URL(`http:${headers.host}${path}`);
}
get query() {
return this.url.searchParams;
}
}
export class Response {
constructor(body, status, headers) {
this.body = body;
if (typeof status === 'number') {
this.status = status;
} else {
this.status = 200;
}
if (headers instanceof Headers) {
this.headers = new Headers(headers);
} else {
this.headers = new Headers();
}
}
send(response) {
if (!(response instanceof OutgoingMessage))
throw new TypeError('Request must be an OutgoingMessage');
for (let [header, value] of this.headers) {
response.setHeader(header, value);
}
response.writeHead(this.status);
if (this.body instanceof Stream) {
this.body.pipe(response);
} else if (this.body instanceof Buffer) {
response.write(this.body);
response.end();
} else {
response.end();
}
return true;
}
}