api.js 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  1. import express from 'express'
  2. import cors from 'cors'
  3. import bodyParser from 'body-parser'
  4. import mongoose from 'mongoose'
  5. import sockjs from 'sockjs'
  6. import configFile from './config/database'
  7. import users from './routes/users'
  8. import swisstennis from './swisstennis'
  9. import sztm from './routes/sztm'
  10. import config from './routes/config'
  11. import { listConfigs } from './routes/config'
  12. import download from './routes/download'
  13. import sms from './routes/sms'
  14. import { authenticate, verify } from './routes/authenticate'
  15. import errorHandler from './middleware/apiErrorHandler'
  16. mongoose.connect(configFile.database)
  17. export const configDb = {}
  18. listConfigs().then(results => {
  19. results.forEach(result => {
  20. configDb[result.key] = { value: result.value, description: result.description }
  21. })
  22. }, error => {
  23. console.log(error)
  24. })
  25. const socketServer = sockjs.createServer({disable_cors: true})
  26. socketServer.on('connection', connection => {
  27. console.log('Connection established', connection.id)
  28. connection.on('close', () => {
  29. console.log('Connection closed', connection.id)
  30. })
  31. connection.on('data', (message) => {
  32. connection.write('Connection message', connection.id, message)
  33. })
  34. })
  35. const port = process.env.PORT || 3002
  36. const app = express()
  37. socketServer.installHandlers(app, { prefix: '/socket' })
  38. app.use(cors())
  39. app.use(bodyParser.urlencoded({ extended: false }))
  40. app.use(bodyParser.json())
  41. app.get('/', (req, res) => {
  42. res.send(`Express API`)
  43. })
  44. // Paths outside the protected zone
  45. app.use('/authenticate', authenticate)
  46. app.use('/download', download)
  47. // Paths inside the protected zone
  48. const apiRoutes = express.Router()
  49. apiRoutes.use('/users', users)
  50. apiRoutes.use('/swisstennis', swisstennis)
  51. apiRoutes.use('/sztm', sztm)
  52. apiRoutes.use('/config', config)
  53. apiRoutes.use('/sms', sms)
  54. // Use verify to protect zone
  55. app.use('/api', verify)
  56. app.use('/api', apiRoutes)
  57. // Catch errors in the error handler
  58. app.use(errorHandler)
  59. app.listen(port)
  60. console.log(`Server running on port ${port}.`)