Showing
1 changed file
with
18 additions
and
2 deletions
1 | const sio = require('socket.io'); | 1 | const sio = require('socket.io'); |
2 | const db = require('./db'); | 2 | const db = require('./db'); |
3 | +const hash = require('./hash'); | ||
3 | 4 | ||
4 | let io; | 5 | let io; |
5 | module.exports = { | 6 | module.exports = { |
6 | init(http) { | 7 | init(http) { |
7 | io = sio(http); | 8 | io = sio(http); |
8 | io.on('connection', (socket) => { | 9 | io.on('connection', (socket) => { |
9 | - socket.on('init', (id) => { | 10 | + socket.on('init', async(id) => { |
11 | + let thread = await db.get('thread').findOne(id); | ||
12 | + if(!thread) { | ||
13 | + socket.close(); | ||
14 | + return; | ||
15 | + } | ||
10 | console.log(`init ${id}`); | 16 | console.log(`init ${id}`); |
11 | - db.get('subthread').find({parent: id}, {sort: '+_id'}).each((thread, _) => { | 17 | + db.get('subthread').find({parent: thread._id}, {sort: '+_id'}).each((thread, _) => { |
12 | socket.emit('thread', thread); | 18 | socket.emit('thread', thread); |
19 | + }).then(() => { | ||
20 | + socket.join(`thread-${thread._id}`); | ||
21 | + console.log(`join thread-${thread._id}`); | ||
22 | + }); | ||
23 | + socket.on('write', async(content) => { | ||
24 | + console.log(`write ${content}`); | ||
25 | + let subthread = await db.get('subthread').insert({parent: thread._id, writer: hash(thread._id, socket.handshake.address), content, no: ++thread.count}); | ||
26 | + db.get('thread').update(thread._id, {$set: {count: thread.count, lastUpdated: Date.now()}}); | ||
27 | + io.to(`thread-${thread._id}`).emit('thread', subthread); | ||
28 | + console.log(`broadcast thread-${thread._id}`); | ||
13 | }); | 29 | }); |
14 | }); | 30 | }); |
15 | }); | 31 | }); | ... | ... |
-
Please register or login to post a comment