-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathserver.ts
80 lines (64 loc) · 2.18 KB
/
server.ts
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
import express from 'express';
import WebSocket from "ws";
// @ts-ignore
import * as ywsUtils from "y-websocket/bin/utils";
// @ts-expect-error
import {applyUpdate, Doc, encodeStateAsUpdate, encodeStateVector} from "yjs";
import {MongodbPersistence} from "y-mongodb-provider";
import dotenv from 'dotenv'
console.log(`Environment: ${process.env.NODE_ENV}`);
const result = dotenv.config();
if (result.error) {
throw result.error;
}
const app = express();
const server = app.listen(process.env.PORT);
const webSocketServer = new WebSocket.Server({server});
console.log(server.address());
app.get('/ping', (_, res) => {
res.send(true);
});
//
webSocketServer.on('connection', (conn: any, req: any) => {
ywsUtils.setupWSConnection(conn, req, {gc: true});
console.log(getStatus());
});
const mongoContext = getMongoContext();
ywsUtils.setPersistence({
bindState: async (docName: string, document: Doc) => {
const persistedDocument = await mongoContext.getYDoc(docName);
const persistedStateVector = encodeStateVector(persistedDocument);
const diff = encodeStateAsUpdate(document, persistedStateVector);
const isDiff = (diff.reduce((previousValue, currentValue) => previousValue + currentValue, 0) > 0);
if (isDiff) {
await mongoContext.storeUpdate(docName, diff);
}
applyUpdate(document, encodeStateAsUpdate(persistedDocument));
document.on('update', async (update) => {
await mongoContext.storeUpdate(docName, update);
});
persistedDocument.destroy();
},
writeState: async (docName: any, document: any) => {
await mongoContext.flushDocument(docName);
}
});
function getMongoContext(): MongodbPersistence {
return new MongodbPersistence(process.env.MONGO_DB_CONNECTION_STRING, {
collectionName: process.env.MONGO_DB_COLLECTION_NAME,
flushSize: 20,
multipleCollections: false
});
}
function getStatus() {
let connections = 0;
const docs = ywsUtils.docs;
docs.forEach((doc: any) => {
connections += doc.conns.size
});
return {
date: new Date().toISOString(),
connections,
docs: docs.size
};
}