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