index.js 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  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. export default 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. }