-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.js
More file actions
66 lines (51 loc) · 1.77 KB
/
Copy pathserver.js
File metadata and controls
66 lines (51 loc) · 1.77 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
import http from 'http';
import fs from 'fs';
import { LiveResponse } from '@webqit/fetch-plus';
import { PGClient } from '@linked-db/linked-ql/postgres';
import { EdgeWorker } from '@linked-db/linked-ql/edge-worker';
import { enableLive, Observer } from '@webqit/node-live-response';
import { setup, cleanup } from '../4_live_queries/setup.js';
const server = http.createServer(handler);
const liveMode = enableLive(server);
server.listen(3000);
console.log('Server started on port 3000');
console.log("Press Ctrl+C to cleanup and exit...");
// ------------
await setup();
const db = new PGClient();
await db.connect();
const httpEdge = EdgeWorker.httpWorker({ db });
const gc = async () => {
await db.disconnect();
await cleanup();
};
process.on('SIGINT', gc);
process.on('SIGTERM', gc);
// ------------
async function handler(req, res) {
if (req.url.split('?')[0] === '/api/db') {
liveMode(req, res);
let livePromise;
const event = {
request: toStandardRequest(req),
client: req.port,
respondWith: (payload) => res.send(new LiveResponse(payload)),
waitUntil: (promise) => livePromise = promise,
};
await httpEdge.handle(event);
Promise.resolve(livePromise).then(async () => {
res.die();
console.log("Live session aborted and connection closed after 10 minutes.");
});
return;
}
return fs.createReadStream('./src/5_remote_querying/index.html').pipe(res);
}
const toStandardRequest = (request) => {
return new Request(`http://localhost${request.url}`, {
method: request.method,
headers: request.headers,
body: ['GET', 'HEAD'].includes(request.method) ? undefined : request,
duplex: 'half',
});
};