-
Notifications
You must be signed in to change notification settings - Fork 7
/
server.js
90 lines (77 loc) · 2.23 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
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
import { DocumentServer, CollabServer, CollabServerPackage, CollabServerConfigurator, series } from 'substance'
import express from 'express'
import path from 'path'
import http from 'http'
import { Server as WebSocketServer } from 'ws'
import seed from './seed'
/*
CollabServerPackage provides an in-memory backend for testing purposes.
For real applications, please provide a custom package here, which configures
a database backend.
*/
let cfg = new CollabServerConfigurator()
cfg.import(CollabServerPackage)
cfg.setHost(process.env.HOST || 'localhost')
cfg.setPort(process.env.PORT || 7777)
/*
Setup Express, HTTP and Websocket Server
*/
let app = express()
let httpServer = http.createServer();
let wss = new WebSocketServer({ server: httpServer })
/*
DocumentServer provides an HTTP API to access snapshots
*/
var documentServer = new DocumentServer({
configurator: cfg
})
documentServer.bind(app)
/*
CollabServer implements the server part of the collab protocol
*/
var collabServer = new CollabServer({
configurator: cfg
})
collabServer.bind(wss)
/*
Serve static files (e.g. the SimpleWriter client)
*/
app.use('/', express.static(path.join(__dirname, '/dist')))
/*
Error handling
We send JSON to the client so they can display messages in the UI.
*/
app.use(function(err, req, res, next) {
if (res.headersSent) {
return next(err)
}
if (err.inspect) {
// This is a SubstanceError where we have detailed info
console.error(err.inspect())
} else {
// For all other errors, let's just print the stack trace
console.error(err.stack)
}
res.status(500).json({
errorName: err.name,
errorMessage: err.message || err.name
})
})
// Delegate http requests to express app
httpServer.on('request', app)
/*
Seeding. This is only necessary with our in-memory stores.
*/
function _runSeed(cb) {
console.info('Seeding database ...')
let changeStore = cfg.getChangeStore()
let snapshotStore = cfg.getSnapshotStore()
seed(changeStore, snapshotStore, cb)
}
function _startServer(cb) {
httpServer.listen(cfg.getPort(), cfg.getHost(), cb)
}
function _whenRunning() {
console.info('Listening on http://' + cfg.getHost() + ':' + httpServer.address().port)
}
series([_runSeed, _startServer], _whenRunning)