dataCollect.js 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687
  1. 'use strict'
  2. import express from 'express'
  3. import boom from '@hapi/boom'
  4. import userAgentParser from 'ua-parser-js'
  5. import { TEST_MODE } from '../../config'
  6. import { COLLECT_DATA } from '../../config.messagesId'
  7. import DataController from '../database/controllers/Data'
  8. import { asyncMiddleware, checkRequiredParameters } from '../functions'
  9. const router = express.Router()
  10. /**
  11. * @api {post} /dataCollect /dataCollect
  12. * @apiVersion 0.1.11
  13. * @apiName dataCollect
  14. * @apiGroup API
  15. *
  16. * @apiDescription Collect user's data
  17. *
  18. * @apiParam {String} uuid The unique user identifier
  19. * @apiParam {Object} screen Screen data, `window.screen` @see https://developer.mozilla.org/en-US/docs/Web/API/Screen
  20. *
  21. * @apiExample Usage example
  22. * 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}}
  23. *
  24. * @apiSuccessExample {string} Success response example
  25. * HTTP/1.1 200 OK /api/dataCollect
  26. * OK
  27. *
  28. * @apiError (Error 4xx) 400_[1] Missing parameter(s)
  29. * @apiErrorExample {json} Missing parameter
  30. * HTTP/1.1 400 Bad Request
  31. * {
  32. * "message": "Missing parameter(s). Required parameters : uuid, screen."
  33. * }
  34. *
  35. * @apiError (Error 4xx) 400_[2] Invalid query parameter
  36. * @apiErrorExample {json} Invalid query parameter(s)
  37. * HTTP/1.1 400 Bad Request
  38. * {
  39. * "message": "Invalid body parameter(s).",
  40. * "data": [
  41. * "\"uuid\" must be a string.",
  42. * "\"screen\" must be a valid object."
  43. * ]
  44. * }
  45. *
  46. */
  47. router.post('/', asyncMiddleware(async (req, res) => {
  48. // Check the request contains all the required body parameters
  49. const b = req.body
  50. checkRequiredParameters(['uuid', 'screen'], b)
  51. let errorList = []
  52. if (typeof b.uuid !== 'string')
  53. errorList.push('"uuid" must be a string.')
  54. if (typeof b.screen !== 'object' || Object.keys(b.screen).length > 30)
  55. errorList.push('"screen" must be a valid object.')
  56. // Check there is no errors with parameters
  57. if (errorList.length > 0)
  58. throw boom.badRequest('Invalid body parameter(s).', errorList)
  59. const userAgent = userAgentParser(req.headers['user-agent'])
  60. // Collected data object
  61. const data = {
  62. uuid: b.uuid,
  63. msgId: COLLECT_DATA,
  64. msg: {
  65. screen: b.screen,
  66. userAgent,
  67. ip: req.ip
  68. }
  69. }
  70. if (!TEST_MODE) await DataController.add(data)
  71. res.send({ message: 'OK' })
  72. }))
  73. export default router