index.js 1.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546
  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 } from './functions'
  10. import { apiPrefix, serverPort, serveClient, imagesPath, logger } from '../config'
  11. const morgan = require('morgan')
  12. const app = express()
  13. // Activating logging
  14. app.use(morgan('combined', { 'stream': { write: (message, encoding) => logger.info(message) } }))
  15. // Use gzip compression to improve performance
  16. app.use(compression())
  17. // Enhance the app security by setting some HTTP headers
  18. app.use(helmet())
  19. if (serveClient) {
  20. // Serve client files (Client is local)
  21. app.use('/', express.static(path.resolve(__dirname, '../dist')))
  22. }
  23. else {
  24. // Don't serve client files (Client is remote)
  25. // Turn "Cross-origin resource sharing" on to allow the remote client to connect to the API
  26. app.use(cors())
  27. }
  28. // Serve images. "serve-static" is used because it caches images ("express.static" doesn't)
  29. app.use(apiPrefix + '/images', serveStatic(imagesPath))
  30. // Load all the API routes in the server
  31. app.use(apiPrefix, routes)
  32. // Error handler (Middleware called when throwing in another middleware)
  33. app.use(errorHandler)
  34. // Start the server on the configured port
  35. app.listen(serverPort, () => logger.info('The server was started on http://localhost:' + serverPort))