_test_functions.js 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. 'use strict'
  2. import path from 'path'
  3. import express from 'express'
  4. import bodyParser from 'body-parser'
  5. import WebSocket from 'ws'
  6. import serveStatic from 'serve-static'
  7. import routes from '../../server/routes'
  8. import { apiPrefix, imageServedUrl, imagesPath } from '../../config'
  9. import connectDb from '../../server/database'
  10. import { errorHandler } from '../../server/functions'
  11. import { errorHandler as wsErrorHandler } from '../../server/webSocket'
  12. import wsMessageHandler from '../../server/webSocket/messageHandler'
  13. // Path to `test` directory
  14. export const testDir = path.resolve(__dirname, '..')
  15. // Pretty-print a JSON object
  16. export const json = obj => 'JSON DATA : ' + (JSON.stringify(obj, null, 2) || obj)
  17. /**
  18. * Open an Express server not listening to any port.
  19. * The server serves images in `test/images`, all api routes and
  20. * uses a custom error handler (no logging to stdout).
  21. *
  22. * Using `request` (supertest) on this object will start the server
  23. * on an ephemeral port.
  24. *
  25. * @param {PluginConfig} plugins plugins that should be loaded with the server
  26. * @returns {object} an Express server
  27. */
  28. export const getHttpServer = () => {
  29. const app = express()
  30. app.use(bodyParser.json())
  31. app.use(imageServedUrl, serveStatic(imagesPath))
  32. app.use(apiPrefix, routes)
  33. app.use(errorHandler)
  34. return app
  35. }
  36. /**
  37. * Open a WebSocket server on top of a HTTP server
  38. *
  39. * @param {object} httpServer a HTTP server instance (ie. Express server object)
  40. * @returns {object} a WebSocket server instance
  41. */
  42. export const getWebSocketServer = httpServer => {
  43. const wss = new WebSocket.Server({ server: httpServer })
  44. wss.on('error', err => {
  45. throw err
  46. })
  47. wss.on('connection', ws => {
  48. ws.on('message', data => wsMessageHandler(ws)(data).catch(wsErrorHandler(ws)))
  49. ws.on('error', wsErrorHandler(ws))
  50. })
  51. return wss
  52. }
  53. /** Connect to the database */
  54. export { connectDb }