messageHandler.js 741 B

123456789101112131415161718192021222324252627282930
  1. 'use strict'
  2. import { formatLog } from '../functions'
  3. import { wsLogger, TEST_MODE } from '../../config'
  4. import DataController from '../database/controllers/Data'
  5. /**
  6. * @typedef {Function} MessageHandler
  7. * @param {string} data a message received from a client
  8. */
  9. /**
  10. * Treat received message from a WebSocket client
  11. * @param {object} ws a WebSocket connected client
  12. * @returns {MessageHandler} the message handler
  13. */
  14. const messageHandler = ws => async data => {
  15. let json
  16. try {
  17. json = JSON.parse(data)
  18. }
  19. catch (err) {
  20. throw new Error('Invalid JSON data.')
  21. }
  22. await DataController.add(json)
  23. if (!TEST_MODE) wsLogger.info(formatLog(json, 'message'))
  24. ws.send('{"message":"ok"}')
  25. }
  26. export default messageHandler