index.js 1.9 KB

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