index.js 1.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546
  1. 'use strict'
  2. import WebSocket from 'ws'
  3. import { formatLog, formatError } from '../functions'
  4. import { wsLogger } 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. 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