index.js 1.8 KB

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