Repository navigation
Expand file tree
/
Copy pathserver.js
More file actions
236 lines (190 loc) · 6.5 KB
/
Copy pathserver.js
File metadata and controls
236 lines (190 loc) · 6.5 KB
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
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
import { createReadStream } from 'node:fs';
import { readFile, stat } from 'node:fs/promises';
import { createServer } from 'node:http';
import { extname, join, normalize, resolve } from 'node:path';
import { fileURLToPath } from 'node:url';
import { proxyRdfResource } from './rdfProxy.js';
const defaultPort = Number(process.env.PORT) || 4173;
const distDir = resolve(fileURLToPath(new URL('./dist', import.meta.url)));
const qudtOrigin = 'https://qudt.org';
const coscineApiOrigin = 'https://coscine.rwth-aachen.de';
const aimsApiOrigin = 'https://aims-backend.tools.coscine.dev';
const contentTypes = new Map([
['.css', 'text/css; charset=utf-8'],
['.html', 'text/html; charset=utf-8'],
['.js', 'text/javascript; charset=utf-8'],
['.json', 'application/json; charset=utf-8'],
['.png', 'image/png'],
['.svg', 'image/svg+xml'],
['.ttl', 'text/turtle; charset=utf-8'],
]);
function send(response, statusCode, body, headers = {}) {
response.writeHead(statusCode, headers);
response.end(body);
}
function getStaticPath(requestPath) {
const decodedPath = decodeURIComponent(requestPath.split('?')[0]);
const normalizedPath = normalize(decodedPath).replace(/^(\.\.[/\\])+/, '');
const relativePath = normalizedPath === '/' ? '/index.html' : normalizedPath;
const filePath = join(distDir, relativePath);
if (!filePath.startsWith(distDir)) {
return null;
}
return filePath;
}
async function readRequestBody(request) {
const chunks = [];
for await (const chunk of request) {
chunks.push(Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk));
}
return Buffer.concat(chunks);
}
function copyProxyHeaders(sourceHeaders) {
const headers = {};
for (const headerName of ['accept', 'authorization', 'content-type']) {
if (sourceHeaders[headerName]) {
headers[headerName] = sourceHeaders[headerName];
}
}
return headers;
}
async function proxyQudt(request, response) {
const targetPath = request.url.replace(/^\/qudt/, '') || '/';
const targetUrl = new URL(targetPath, qudtOrigin);
const upstreamResponse = await fetch(targetUrl, {
headers: {
Accept: request.headers.accept || 'text/turtle, */*;q=0.1',
},
});
const headers = Object.fromEntries(upstreamResponse.headers.entries());
delete headers['content-encoding'];
delete headers['content-length'];
headers['access-control-allow-origin'] = '*';
response.writeHead(upstreamResponse.status, headers);
if (upstreamResponse.body) {
for await (const chunk of upstreamResponse.body) {
response.write(chunk);
}
}
response.end();
}
async function proxyAims(request, response) {
const targetPath = request.url.replace(/^\/aims-api/, '') || '/';
const targetUrl = new URL(targetPath, aimsApiOrigin);
const upstreamResponse = await fetch(targetUrl, {
headers: {
Accept: request.headers.accept || 'application/json',
},
});
const headers = Object.fromEntries(upstreamResponse.headers.entries());
delete headers['content-encoding'];
delete headers['content-length'];
headers['access-control-allow-origin'] = '*';
response.writeHead(upstreamResponse.status, headers);
if (upstreamResponse.body) {
for await (const chunk of upstreamResponse.body) {
response.write(chunk);
}
}
response.end();
}
async function proxyCoscine(request, response) {
const targetPath = request.url.replace(/^\/coscine-api/, '/coscine/api/v2') || '/';
const targetUrl = new URL(targetPath, coscineApiOrigin);
const hasRequestBody = !['GET', 'HEAD'].includes(request.method);
const requestBody = hasRequestBody ? await readRequestBody(request) : undefined;
const headers = copyProxyHeaders(request.headers);
if (requestBody) {
headers['content-length'] = String(requestBody.byteLength);
}
const upstreamResponse = await fetch(targetUrl, {
method: request.method,
headers,
body: requestBody,
});
const responseHeaders = Object.fromEntries(upstreamResponse.headers.entries());
delete responseHeaders['content-encoding'];
delete responseHeaders['content-length'];
responseHeaders['access-control-allow-origin'] = '*';
response.writeHead(upstreamResponse.status, responseHeaders);
if (upstreamResponse.body) {
for await (const chunk of upstreamResponse.body) {
response.write(chunk);
}
}
response.end();
}
async function serveStatic(request, response) {
const filePath = getStaticPath(request.url);
if (!filePath) {
send(response, 403, 'Forbidden');
return;
}
try {
const fileStat = await stat(filePath);
if (!fileStat.isFile()) {
throw new Error('Not a file.');
}
response.writeHead(200, {
'Content-Type': contentTypes.get(extname(filePath)) || 'application/octet-stream',
});
createReadStream(filePath).pipe(response);
} catch {
const indexHtml = await readFile(join(distDir, 'index.html'));
response.writeHead(200, {
'Content-Type': 'text/html; charset=utf-8',
});
response.end(indexHtml);
}
}
export function createTabularRdmServer() {
return createServer(async (request, response) => {
try {
if (request.url.startsWith('/rdf-resource')) {
await proxyRdfResource(request, response);
return;
}
if (request.url.startsWith('/aims-api')) {
await proxyAims(request, response);
return;
}
if (request.url.startsWith('/qudt')) {
await proxyQudt(request, response);
return;
}
if (request.url.startsWith('/coscine-api')) {
await proxyCoscine(request, response);
return;
}
await serveStatic(request, response);
} catch (error) {
send(response, 502, error?.message || 'Proxy request failed.');
}
});
}
export function startTabularRdmServer({ port = defaultPort, host = '127.0.0.1' } = {}) {
const server = createTabularRdmServer();
return new Promise((resolveStart, rejectStart) => {
const handleError = (error) => {
rejectStart(error);
};
server.once('error', handleError);
server.listen(port, host, () => {
server.off('error', handleError);
const address = server.address();
const selectedPort = typeof address === 'object' && address ? address.port : port;
resolveStart({
server,
url: `http://${host}:${selectedPort}`,
});
});
});
}
const isCommandLineEntry = process.argv[1]
? resolve(process.argv[1]) === fileURLToPath(import.meta.url)
: false;
if (isCommandLineEntry) {
startTabularRdmServer().then(({ url }) => {
console.log(`TabularRDM server listening on ${url}`);
});
}