messageHandler.js 821 B

1234567891011121314151617181920212223242526272829303132
  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. if (!TEST_MODE && !json.uuid)
  23. throw new Error('"uuid" was not provided.')
  24. await DataController.add(json)
  25. if (!TEST_MODE) wsLogger.info(formatLog(json, 'message'))
  26. ws.send('{"message":"ok"}')
  27. }
  28. export default messageHandler