-
Notifications
You must be signed in to change notification settings - Fork 0
/
server.js
63 lines (54 loc) · 1.5 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
const http = require('http');
const path = require('path');
const express = require('express');
const ShareDB = require('sharedb');
const WS = require('ws');
const WebSocketJSONStream = require('@teamwork/websocket-json-stream');
const shortid = require('shortid');
const OT = require('./ot.js');
const backend = new ShareDB({
presence: true,
});
const connection = backend.connect();
const app = express();
// static
const static = express.static('static');
app.use(static);
// client
app.post("/client", (req, res) => {
const id = shortid.generate();
res.redirect(`/client/${id}`);
});
const clientPage = path.resolve(__dirname, "static/client.html");
app.use("/client/:id", (req, res) => {
const id = req.params.id;
const doc = connection.get("codemirror", id);
// console.log(id, doc.type);
if (doc.type === null) {
doc.create("// hello world", OT.type.name, (err) => {
if (err) {
console.error(`error while creating doc "${id}"`, err);
} else {
console.log(`doc "${id}" created`);
}
});
}
res.sendFile(clientPage);
// res.redirect(`/client.html?id=${id}`);
});
const server = http.createServer(app);
const wss = new WS.Server({
server: server,
path: "/client"
});
wss.on('connection', (ws) => {
const stream = new WebSocketJSONStream(ws);
backend.listen(stream);
});
const port = 8080;
server.listen(port);
console.debug(`Listening on ${port}`);
process.on('SIGINT', function () {
console.log("SIGINT received, exiting...");
process.exit();
});