All files / pages/api socket.js

0% Statements 0/37
0% Branches 0/6
0% Functions 0/10
0% Lines 0/37

Press n or j to go to the next uncovered block, b, p or k for the previous block.

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                                                                                                                                                       
import { Server } from 'socket.io'
import dojoDomains from '../../lib/dojoDomains'
 
let rooms = {}
 
export default function SocketHandler(req, res) {
  if (res.socket.server.io) {
    res.end()
    return
  }
 
  const io = new Server(res.socket.server)
  res.socket.server.io = io
 
  io.on('connection', (socket) => {
    socket.on('join-room', ({ room, user, domain }) => {
      if (!(room in rooms)) {
        rooms[room] = {
          connections: {
            [socket.id]: { admin: true, user, belt: '' },
          },
          domain,
          principle: Object.keys(dojoDomains[domain])[0],
          chat: [],
          votes: {},
        }
      } else {
        rooms[room].connections[socket.id] = { user, belt: '' }
      }
      socket.join(room)
      io.to(room).emit('room-data', rooms[room])
    })
 
    socket.on('select-belt-colour', ({ room, colour }) => {
      rooms[room].connections[socket.id].belt = colour
      io.to(room).emit('room-data', rooms[room])
    })
 
    socket.on('hide-cards', ({ room, hide }) => {
      io.to(room).emit('hide-from-server', hide)
    })
 
    socket.on('clear-cards', ({ room }) => {
      for (let id in rooms[room].connections) {
        rooms[room].connections[id].belt = ''
      }
      io.to(room).emit('room-data', rooms[room])
    })
 
    socket.on('update-timer', ({ room, timer }) => {
      io.to(room).emit('update-timer-from-server', timer - 1)
    })
 
    socket.on('leave-room', ({ room }) => {
      delete rooms[room].connections[socket.id]
      if (!Object.keys(rooms[room].connections).length) {
        delete rooms[room]
      }
      socket.leave(room)
      io.to(room).emit('room-data', rooms[room])
    })
 
    socket.on('chat-message', ({ room, msg }) => {
      rooms[room].chat.push({ id: socket.id, msg })
      io.to(room).emit('room-data', rooms[room])
    })
 
    socket.on('set-principle', ({ room, newPrinciple }) => {
      rooms[room].principle = newPrinciple
      io.to(room).emit('room-data', rooms[room])
    })
  })
 
  res.end()
}