index.js 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152
  1. 'use strict'
  2. import path from 'path'
  3. import express from 'express'
  4. import compression from 'compression'
  5. import serveStatic from 'serve-static'
  6. import helmet from 'helmet'
  7. import cors from 'cors'
  8. import routes from './routes'
  9. import { errorHandler } from './functions'
  10. import { apiPrefix, imageServedUrl, serverPort, serveClient, imagesPath, logger } from '../config'
  11. import startWebSocketServer from './webSocket'
  12. const morgan = require('morgan')
  13. const app = express()
  14. // Activating logging
  15. app.use(morgan('combined', {
  16. stream: { write: message => logger.info(message) }
  17. }))
  18. // Use gzip compression to improve performance
  19. app.use(compression())
  20. // Enhance the app security by setting some HTTP headers
  21. app.use(helmet())
  22. // Serve images. "serve-static" is used because it caches images ("express.static" doesn't)
  23. app.use(imageServedUrl, serveStatic(imagesPath))
  24. // Load all the API routes in the server
  25. app.use(apiPrefix, routes)
  26. if (serveClient) {
  27. // Serve client files (Client is local)
  28. app.use('/', express.static(path.resolve(__dirname, '../dist')))
  29. }
  30. else {
  31. // Don't serve client files (Client is remote)
  32. // Turn "Cross-origin resource sharing" on to allow the remote client to connect to the API
  33. app.use(cors())
  34. app.get('*', (req, res) => res.status(404).send('Client is not served.'))
  35. }
  36. // Error handler (Middleware called when throwing in another middleware)
  37. app.use(errorHandler)
  38. // Start the server on the configured port
  39. const server = app.listen(serverPort, () => logger.info('The server was started on http://localhost:' + serverPort))
  40. // Start the WebSocket server on top of the started HTTP server
  41. startWebSocketServer(server)