_test_functions.js 1.9 KB

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