experimentCollect.js 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. 'use strict'
  2. import express from 'express'
  3. import boom from '@hapi/boom'
  4. import { TEST_MODE } from '../../config'
  5. import DataController from '../database/controllers/Data'
  6. import { asyncMiddleware, checkRequiredParameters } from '../functions'
  7. const router = express.Router()
  8. /**
  9. * @api {post} /experimentCollect /experimentCollect
  10. * @apiVersion 0.1.11
  11. * @apiName experimentCollect
  12. * @apiGroup API
  13. *
  14. * @apiDescription Collect user's data
  15. *
  16. * @apiParam {String} msgId The type of message to store
  17. * @apiParam {any} Any data that needs to be stored
  18. *
  19. * @apiExample Usage example
  20. * curl -i -L -H "Content-Type: application/json" -X POST "https://diran.univ-littoral.fr/api/experimentCollect" -d {"msgId":"test","msg":{}}
  21. *
  22. * @apiSuccessExample {string} Success response example
  23. * HTTP/1.1 204 OK /api/experimentCollect
  24. *
  25. * @apiError (Error 4xx) 400_[1] Missing parameter(s)
  26. * @apiErrorExample {json} Missing parameter
  27. * HTTP/1.1 400 Bad Request
  28. * {
  29. * "message": "Missing parameter(s). Required parameters : msgId, msg."
  30. * }
  31. *
  32. * @apiError (Error 4xx) 400_[2] Invalid query parameter
  33. * @apiErrorExample {json} Invalid query parameter(s)
  34. * HTTP/1.1 400 Bad Request
  35. * {
  36. * "message": "Invalid body parameter(s).",
  37. * "data": [
  38. * "\"msgId\" must be a string."
  39. * ]
  40. * }
  41. *
  42. */
  43. router.post('/', asyncMiddleware(async (req, res) => {
  44. // Check the request contains all the required body parameters
  45. const b = req.body
  46. checkRequiredParameters(['msgId', 'msg'], b)
  47. const {
  48. msgId,
  49. msg,
  50. userId = null,
  51. experimentId = null
  52. } = req.body
  53. // Check there is no errors with parameters
  54. if (typeof b.msgId !== 'string')
  55. throw boom.badRequest('Invalid body parameter(s).', ['"msgId" must be a string.'])
  56. // Add data to the database
  57. if (!TEST_MODE) await DataController.add({ msgId, msg, userId, experimentId })
  58. res.status(204).send()
  59. }))
  60. export default router