experimentCollect.js 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  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 { msgId, msg } = req.body
  48. // Check there is no errors with parameters
  49. if (typeof b.msgId !== 'string')
  50. throw boom.badRequest('Invalid body parameter(s).', ['"msgId" must be a string.'])
  51. // Add data to the database
  52. if (!TEST_MODE) await DataController.add({ msgId, msg })
  53. res.status(204).send()
  54. }))
  55. export default router