forked from tomphttp/bare-server-node
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathServer.js
169 lines (150 loc) · 4.09 KB
/
Server.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
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
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
import register_v1 from './V1.js';
import register_v2 from './V2.js';
import { Request, Response } from './AbstractMessage.js';
export default class Server {
prefix = '/';
fof = this.json(404, { message: 'Not found.' });
maintainer = undefined;
project = {
name: 'TOMPHTTP NodeJS Bare Server',
repository: 'https://github.com/tomphttp/bare-server-node',
};
log_errors = false;
local_address = undefined;
routes = new Map();
socket_routes = new Map();
constructor(directory, log_errors, local_address, maintainer) {
if (log_errors === true) {
this.log_errors = true;
}
if (typeof local_address === 'string') {
this.local_address = local_address;
}
if (typeof maintainer === 'object' && maintainer === null) {
this.maintainer = maintainer;
}
if (typeof directory !== 'string') {
throw new Error('Directory must be specified.');
}
if (!directory.startsWith('/') || !directory.endsWith('/')) {
throw new RangeError('Directory must start and end with /');
}
this.directory = directory;
this.routes.set('/', () => {
return this.json(200, this.instance_info);
});
register_v1(this);
register_v2(this);
}
error(...args) {
if (this.log_errors) {
console.error(...args);
}
}
json(status, json) {
const send = Buffer.from(JSON.stringify(json, null, '\t'));
return new Response(send, status, {
'content-type': 'application/json',
'content-length': send.byteLength,
});
}
route_request(request, response) {
if (request.url.startsWith(this.directory)) {
this.request(request, response);
return true;
} else {
return false;
}
}
route_upgrade(request, socket, head) {
if (request.url.startsWith(this.directory)) {
this.upgrade(request, socket, head);
return true;
} else {
return false;
}
}
get instance_info() {
return {
versions: ['v1', 'v2'],
language: 'NodeJS',
memoryUsage:
Math.round((process.memoryUsage().heapUsed / 1024 / 1024) * 100) / 100,
maintainer: this.maintainer,
developer: this.project,
};
}
async upgrade(client_request, client_socket, client_head) {
const request = new Request(
client_request,
client_request.method,
client_request.url,
client_request.headers
);
const service = request.url.pathname.slice(this.directory.length - 1);
if (this.routes.has(service)) {
const call = this.socket_routes.get(service);
try {
await call(this, request, client_socket, client_head);
} catch (error) {
this.error(error);
client_socket.end();
}
} else {
client_socket.end();
}
}
/**
*
* @param {import('node:http').ClientRequest} server_request
* @param {import('node:http').ServerResponse} server_response
*/
async request(client_request, server_response) {
const request = new Request(
client_request,
client_request.method,
client_request.url,
client_request.headers
);
const service = request.url.pathname.slice(this.directory.length - 1);
let response;
if (this.routes.has(service)) {
const call = this.routes.get(service);
try {
response = await call(this, request);
} catch (error) {
this.error(error);
if (error instanceof Error) {
response = this.json(500, {
code: 'UNKNOWN',
id: `error.${error.name}`,
message: error.message,
stack: error.stack,
});
} else {
response = this.json(500, {
code: 'UNKNOWN',
id: 'error.Exception',
message: error,
stack: new Error(error).stack,
});
}
}
} else {
response = this.fof;
}
if (!(response instanceof Response)) {
this.error('Data', server_request.url, 'was not a response.');
response = this.fof;
}
response.headers.set('x-robots-tag', 'noindex');
response.headers.set('access-control-allow-headers', '*');
response.headers.set('access-control-allow-origin', '*');
response.headers.set('access-control-allow-methods', '*');
response.headers.set('access-control-expose-headers', '*');
// don't send preflight on every request...
// instead, send preflight every 10 minutes
response.headers.set('access-control-max-age', '7200');
response.send(server_response);
}
}