dataCollect.js 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. 'use strict'
  2. import express from 'express'
  3. import boom from '@hapi/boom'
  4. import userAgentParser from 'ua-parser-js'
  5. import { COLLECT_DATA } from '../../config.messagesId'
  6. import DataController from '../database/controllers/Data'
  7. import { asyncMiddleware, checkRequiredParameters } from '../functions'
  8. const router = express.Router()
  9. /**
  10. * @api {post} /dataCollect /dataCollect
  11. * @apiVersion 0.1.11
  12. * @apiName dataCollect
  13. * @apiGroup API
  14. *
  15. * @apiDescription Collect user's data
  16. *
  17. * @apiExample Usage example
  18. * curl -i -L -H "Content-Type: application/json" -X POST "http://diran.univ-littoral.fr/api/dataCollect" -d '{"uuid":"test","viewport":{"x":1920,"y":1024}}'
  19. *
  20. * @apiSuccessExample {string} Success response example
  21. * HTTP/1.1 200 OK /api/dataCollect
  22. * OK
  23. */
  24. router.post('/', asyncMiddleware(async (req, res) => {
  25. // Check the request contains all the required body parameters
  26. const b = req.body
  27. checkRequiredParameters(['uuid', 'viewport'], b)
  28. let errorList = []
  29. if (typeof b.uuid !== 'string')
  30. errorList.push('"uuid" must be a string.')
  31. if (!Number.isInteger(b.viewport.x) || !Number.isInteger(b.viewport.y))
  32. errorList.push('"viewport.x" and "viewport.y" must be integers.')
  33. // Check there is no errors with parameters
  34. if (errorList.length > 0)
  35. throw boom.badRequest('Invalid body parameter(s).', errorList)
  36. const userAgent = userAgentParser(req.headers['user-agent'])
  37. // Collected data object
  38. const data = {
  39. uuid: b.uuid,
  40. msgId: COLLECT_DATA,
  41. msg: {
  42. viewport: b.viewport,
  43. userAgent,
  44. ip: req.ip
  45. }
  46. }
  47. await DataController.add(data)
  48. res.send('OK')
  49. }))
  50. export default router