socket.js 1.36 KB
const sio = require('socket.io');
const db = require('./db');
const hash = require('./hash');

let io;
module.exports = {
    init(http) {
        io = sio(http);
        io.on('connection', (socket) => {
            socket.on('init', async(id) => {
                let thread = await db.get('thread').findOne(id);
                if(!thread) {
                    socket.close();
                    return;
                }
                console.log(`init ${id}`);
                db.get('subthread').find({parent: thread._id}, {sort: '+_id'}).each((thread, _) => {
                    socket.emit('thread', thread);
                }).then(() => {
                    socket.join(`thread-${thread._id}`);
                    console.log(`join thread-${thread._id}`);
                });
                socket.on('write', async(content) => {
                    console.log(`write ${content}`);
                    let subthread = await db.get('subthread').insert({parent: thread._id, writer: hash(thread._id, socket.handshake.address), content, no: ++thread.count});
                    db.get('thread').update(thread._id, {$set: {count: thread.count, lastUpdated: Date.now()}});
                    io.to(`thread-${thread._id}`).emit('thread', subthread);
                    console.log(`broadcast thread-${thread._id}`);
                });
            });
        });
    }
};