-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.coffee
80 lines (70 loc) · 2.55 KB
/
index.coffee
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
cors = require('cors')
app = require('express')();
bodyParser = require('body-parser')
app.use(cors({origin: true, credentials: true})) # Enable CORS across the entire express app
app.use(bodyParser.json())
mongoose = require('mongoose');
mongoose.connect('mongodb://localhost/typeset', (err) ->
if err
console.log('MongoDB connection failed!')
else
console.log('MongoDB Connected!')
server = app.listen(8888, -> console.log('Listening on port ' + 8888))
io = require('socket.io')(server);
io.on('connection', (socket) ->
console.log('New Socket Connected!')
# Attach the document handler events
require('./lib/doc')(socket, mongoose)
socket.on('disconnect', (socket) ->
console.log('Socket Disconnected!')
)
)
# Obtain the Document model
Document = require('./lib/models/Document')(mongoose)
namespaces = []
namespaceDefined = (docid) -> namespaces.indexOf(docid) >= 0
# POST confirmation to create the socket namespace for
# the particular document type.
app.post('/research', (req, res) ->
Composer = require('./lib/research-delta-composer')(mongoose)
docid = req.param('docid')
# TODO: Check for document existence and editing rights
console.log('Setting up namespace for: ' + docid)
Document.findOne({_id: docid}, (err, document) ->
if err or not document
console.log('Failed to setup namespace: ' + docid)
res.json({
code: 400
error: 'Invalid Document'
})
else
# Create a namespace for that socket and attach handlers, then respond
if not namespaceDefined(docid)
docSock = io.of('/' + docid)
namespaces.push(docid)
docSock.on('connection', (socket) ->
console.log('Socket connected for document: ' + docid)
require('./lib/research-editor')(socket, mongoose, document)
socket.on('disconnect', (socket) ->
console.log('Disconnected socket for ' + docid)
)
)
Composer.compose(docid, 0, (err, document) ->
res.json({
code: 200
data: document
})
)
console.log('Setup namespace: ' + docid)
else
console.log('namespace and handler defined already!')
Composer.compose(docid, 0, (err, document) ->
res.json({
code: 200
data: document
})
)
)
)
return
);