index.js 1.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546
  1. 'use strict'
  2. import WebSocket from 'ws'
  3. import { formatLog, formatError } from '../functions'
  4. import { wsLogger, TEST_MODE } from '../../config'
  5. import messageHandler from './messageHandler'
  6. /**
  7. * @typedef {function} ErrorLogger
  8. * @param {Error} err an Error object
  9. */
  10. /**
  11. * Handle thrown errors
  12. *
  13. * @param {object} ws a WebSocket connected client
  14. * @returns {ErrorLogger} the actual error logger
  15. */
  16. export const errorHandler = ws => err => {
  17. const errStr = formatError(err)
  18. ws.send(JSON.stringify(errStr))
  19. if (!TEST_MODE) wsLogger.error(errStr)
  20. }
  21. /**
  22. * Create the WebSocket server
  23. *
  24. * @param {*} httpServer an HTTP node object (provided by Express here)
  25. * @returns {void}
  26. */
  27. const createWsServer = httpServer => {
  28. const wss = new WebSocket.Server({ server: httpServer })
  29. wss.on('listening', () => wsLogger.info(formatLog('The WebSocket server was started')))
  30. wss.on('error', err => wsLogger.error(formatError(err)))
  31. wss.on('connection', ws => {
  32. wsLogger.info(formatLog('New client connected.'))
  33. ws.on('message', data => messageHandler(ws)(data).catch(err => errorHandler(ws)(err)))
  34. ws.on('error', err => errorHandler(ws)(err))
  35. ws.on('close', () => wsLogger.info(formatLog('Client disconnected.')))
  36. })
  37. }
  38. export default createWsServer