index.js 1.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445
  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. ws.send(err.message)
  18. if (!TEST_MODE) wsLogger.error(formatError(err))
  19. }
  20. /**
  21. * Create the WebSocket server
  22. *
  23. * @param {*} httpServer an HTTP node object (provided by Express here)
  24. * @returns {void}
  25. */
  26. const createWsServer = httpServer => {
  27. const wss = new WebSocket.Server({ server: httpServer })
  28. wss.on('listening', () => wsLogger.info(formatLog('The WebSocket server was started')))
  29. wss.on('error', err => wsLogger.error(formatError(err)))
  30. wss.on('connection', ws => {
  31. wsLogger.info(formatLog('New client connected.'))
  32. ws.on('message', data => messageHandler(ws)(data).catch(err => errorHandler(ws)(err)))
  33. ws.on('error', err => errorHandler(ws)(err))
  34. ws.on('close', () => wsLogger.info(formatLog('Client disconnected.')))
  35. })
  36. }
  37. export default createWsServer