index.js 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  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. // Turn "Cross-origin resource sharing" on to allow remote clients to connect to the API
  24. app.use(cors())
  25. // Serve images. "serve-static" is used because it caches images ("express.static" doesn't)
  26. app.use(imageServedUrl, serveStatic(imagesPath))
  27. // Load all the API routes in the server
  28. app.use(apiPrefix, routes)
  29. // Serve documentation
  30. app.use('/doc', express.static(path.resolve(__dirname, '../doc')))
  31. // Serve client files
  32. if (serveClient) app.use('/', express.static(path.resolve(__dirname, '../dist')))
  33. else app.get('*', (req, res) => res.status(404).send('Client is not served.'))
  34. // Error handler (Middleware called when throwing in another middleware)
  35. app.use(errorHandler)
  36. const setup = async () => {
  37. // Connect to the MongoDB database
  38. await connectDb()
  39. // Start the server on the configured port
  40. const server = app.listen(serverPort, () => logger.info(formatLog(`The server was started on http://localhost:${serverPort}`)))
  41. // Start the WebSocket server on top of the started HTTP server
  42. startWebSocketServer(server)
  43. }
  44. setup()