Parcourir la source

Removed websocket server and added API route

rigwild il y a 4 ans
Parent
commit
aade695dba

+ 1 - 5
server/index.js

@@ -11,7 +11,6 @@ import bodyParser from 'body-parser'
 import routes from './routes'
 import { errorHandler, formatLog } from './functions'
 import { apiPrefix, imageServedUrl, serverPort, serveClient, imagesPath, logger } from '../config'
-import startWebSocketServer from './webSocket'
 import connectDb from './database'
 const morgan = require('morgan')
 
@@ -56,8 +55,5 @@ export default async () => {
   await connectDb()
 
   // Start the server on the configured port
-  const server = app.listen(serverPort, () => logger.info(formatLog(`The server was started on http://localhost:${serverPort}`)))
-
-  // Start the WebSocket server on top of the started HTTP server
-  startWebSocketServer(server)
+  app.listen(serverPort, () => logger.info(formatLog(`The server was started on http://localhost:${serverPort}`)))
 }

+ 65 - 0
server/routes/experimentCollect.js

@@ -0,0 +1,65 @@
+'use strict'
+
+import express from 'express'
+import boom from '@hapi/boom'
+
+import { TEST_MODE } from '../../config'
+import DataController from '../database/controllers/Data'
+import { asyncMiddleware, checkRequiredParameters } from '../functions'
+
+const router = express.Router()
+
+/**
+ * @api {post} /experimentCollect /experimentCollect
+ * @apiVersion 0.1.11
+ * @apiName experimentCollect
+ * @apiGroup API
+ *
+ * @apiDescription Collect user's data
+ *
+ * @apiParam {String} msgId The type of message to store
+ * @apiParam {any} Any data that needs to be stored
+ *
+ * @apiExample Usage example
+ * curl -i -L -H "Content-Type: application/json" -X POST "http://diran.univ-littoral.fr/api/experimentCollect" -d {"msgId":"test","msg":{}}
+ *
+ * @apiSuccessExample {string} Success response example
+ * HTTP/1.1 204 OK /api/experimentCollect
+ *
+ * @apiError (Error 4xx) 400_[1] Missing parameter(s)
+ * @apiErrorExample {json} Missing parameter
+ * HTTP/1.1 400 Bad Request
+ * {
+ *   "message": "Missing parameter(s). Required parameters : msgId, msg."
+ * }
+ *
+ * @apiError (Error 4xx) 400_[2] Invalid query parameter
+ * @apiErrorExample {json} Invalid query parameter(s)
+ * HTTP/1.1 400 Bad Request
+ * {
+ *   "message": "Invalid body parameter(s).",
+ *   "data": [
+ *     "\"msgId\" must be a string."
+ *   ]
+ * }
+ *
+ */
+
+router.post('/', asyncMiddleware(async (req, res) => {
+  // Check the request contains all the required body parameters
+  const b = req.body
+  checkRequiredParameters(['msgId', 'msg'], b)
+
+  const { msgId, msg } = req.body
+
+  // Check there is no errors with parameters
+  if (typeof b.msgId !== 'string')
+    throw boom.badRequest('Invalid body parameter(s).', ['"msgId" must be a string.'])
+
+  // Add data to the database
+  if (!TEST_MODE) await DataController.add({ msgId, msg })
+
+  res.status(204).send()
+}))
+
+export default router

+ 2 - 0
server/routes/index.js

@@ -7,6 +7,7 @@ import getImage from './getImage'
 import getImageExtracts from './getImageExtracts'
 import ping from './ping'
 import dataCollect from './dataCollect'
+import experimentCollect from './experimentCollect'
 
 const router = express.Router()
 
@@ -15,6 +16,7 @@ router.use('/listSceneQualities', listSceneQualities)
 router.use('/getImage', getImage)
 router.use('/getImageExtracts', getImageExtracts)
 router.use('/dataCollect', dataCollect)
+router.use('/experimentCollect', experimentCollect)
 router.use('/ping', ping)
 
 export default router

+ 0 - 46
server/webSocket/index.js

@@ -1,46 +0,0 @@
-'use strict'
-
-import WebSocket from 'ws'
-import { formatLog, formatError } from '../functions'
-import { wsLogger, TEST_MODE } from '../../config'
-import messageHandler from './messageHandler'
-
-/**
- * @typedef {function} ErrorLogger
- * @param {Error} err an Error object
- */
-/**
- * Handle thrown errors
- *
- * @param {object} ws a WebSocket connected client
- * @returns {ErrorLogger} the actual error logger
- */
-export const errorHandler = ws => err => {
-  const errStr = formatError(err)
-  ws.send(JSON.stringify(errStr))
-  if (!TEST_MODE) wsLogger.error(errStr)
-}
-
-/**
- * Create the WebSocket server
- *
- * @param {*} httpServer an HTTP node object (provided by Express here)
- * @returns {void}
- */
-const createWsServer = httpServer => {
-  const wss = new WebSocket.Server({ server: httpServer })
-
-  wss.on('listening', () => wsLogger.info(formatLog('The WebSocket server was started')))
-  wss.on('error', err => wsLogger.error(formatError(err)))
-
-  wss.on('connection', ws => {
-    wsLogger.info(formatLog('New client connected.'))
-
-    ws.on('message', data => messageHandler(ws)(data).catch(err => errorHandler(ws)(err)))
-
-    ws.on('error', err => errorHandler(ws)(err))
-    ws.on('close', () => wsLogger.info(formatLog('Client disconnected.')))
-  })
-}
-
-export default createWsServer

+ 0 - 32
server/webSocket/messageHandler.js

@@ -1,32 +0,0 @@
-'use strict'
-
-import { formatLog } from '../functions'
-import { wsLogger, TEST_MODE } from '../../config'
-import DataController from '../database/controllers/Data'
-
-/**
- * @typedef {Function} MessageHandler
- * @param {string} data a message received from a client
- */
-/**
- * Treat received message from a WebSocket client
- * @param {object} ws a WebSocket connected client
- * @returns {MessageHandler} the message handler
- */
-const messageHandler = ws => async data => {
-  let json
-  try {
-    json = JSON.parse(data)
-  }
-  catch (err) {
-    throw new Error('Invalid JSON data.')
-  }
-  if (!TEST_MODE && !json.uuid)
-    throw new Error('"uuid" was not provided.')
-
-  await DataController.add(json)
-  if (!TEST_MODE) wsLogger.info(formatLog(json, 'message'))
-  ws.send('{"message":"ok"}')
-}
-
-export default messageHandler