This repository was archived by the owner on Feb 1, 2019. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathserver.js
67 lines (54 loc) · 1.61 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
const http = require('http')
const Duplex = require('stream').Duplex
const inherits = require('util').inherits
const ShareDB = require('sharedb')
const db = require('sharedb-mongo')
const pubsub = require('sharedb-redis-pubsub')
const WebSocketServer = require('ws').Server
const otText = require('ot-text')
ShareDB.types.map['json0'].registerSubtype(otText.type)
const shareDB = ShareDB({
db: db(process.env.MONGO_URL),
pubsub: pubsub({
url: process.env.REDIS_URL
})
})
const server = http.createServer()
server.listen(process.env.NODE_PORT, function (err) {
if (err) { throw err }
console.log("Listening on port " + server.address().port);
})
const webSocketServer = new WebSocketServer({
server: server,
verifyClient: function(info) {
return info.req.headers.origin.includes(process.env.ORIGIN_URL);
}
})
webSocketServer.on('connection', function (socket) {
var stream = new WebsocketJSONOnWriteStream(socket)
shareDB.listen(stream)
})
function WebsocketJSONOnWriteStream(socket) {
Duplex.call(this, {objectMode: true})
this.socket = socket
const stream = this
socket.on('message', function(data) {
stream.push(data)
})
socket.on("close", function() {
stream.push(null)
})
this.on("error", function(msg) {
console.warn('WebsocketJSONOnWriteStream error', msg)
socket.close()
})
this.on("end", function() {
socket.close()
})
}
inherits(WebsocketJSONOnWriteStream, Duplex)
WebsocketJSONOnWriteStream.prototype._write = function(value, encoding, next) {
this.socket.send(JSON.stringify(value))
next()
}
WebsocketJSONOnWriteStream.prototype._read = function() {}