dataCollect.js 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  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. * @apiParam {String} uuid The unique user identifier
  18. * @apiParam {Object} screen Screen data, `window.screen` @see https://developer.mozilla.org/en-US/docs/Web/API/Screen
  19. *
  20. * @apiExample Usage example
  21. * curl -i -L -H "Content-Type: application/json" -X POST "http://diran.univ-littoral.fr/api/dataCollect" -d {"uuid":"test","screen":{"width":1920,"height":1024}}
  22. *
  23. * @apiSuccessExample {string} Success response example
  24. * HTTP/1.1 200 OK /api/dataCollect
  25. * OK
  26. *
  27. * @apiError (Error 4xx) 400_[1] Missing parameter(s)
  28. * @apiErrorExample {json} Missing parameter
  29. * HTTP/1.1 400 Bad Request
  30. * {
  31. * "message": "Missing parameter(s). Required parameters : uuid, screen."
  32. * }
  33. *
  34. * @apiError (Error 4xx) 400_[2] Invalid query parameter
  35. * @apiErrorExample {json} Invalid query parameter(s)
  36. * HTTP/1.1 400 Bad Request
  37. * {
  38. * "message": "Invalid body parameter(s).",
  39. * "data": [
  40. * "\"uuid\" must be a string.",
  41. * "\"screen\" must be a valid object."
  42. * ]
  43. * }
  44. *
  45. */
  46. router.post('/', asyncMiddleware(async (req, res) => {
  47. // Check the request contains all the required body parameters
  48. const b = req.body
  49. checkRequiredParameters(['uuid', 'screen'], b)
  50. let errorList = []
  51. if (typeof b.uuid !== 'string')
  52. errorList.push('"uuid" must be a string.')
  53. if (!Object.isObject(b.screen) || Object.keys(b.screen).length > 30)
  54. errorList.push('"screen" must be a valid object.')
  55. // Check there is no errors with parameters
  56. if (errorList.length > 0)
  57. throw boom.badRequest('Invalid body parameter(s).', errorList)
  58. const userAgent = userAgentParser(req.headers['user-agent'])
  59. // Collected data object
  60. const data = {
  61. uuid: b.uuid,
  62. msgId: COLLECT_DATA,
  63. msg: {
  64. screen: b.screen,
  65. userAgent,
  66. ip: req.ip
  67. }
  68. }
  69. await DataController.add(data)
  70. res.send('OK')
  71. }))
  72. export default router