index.js 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253
  1. const express = require('express')
  2. const bodyParser = require('body-parser')
  3. const sockjs = require('sockjs')
  4. const http = require('http')
  5. const mongoose = require('mongoose')
  6. /** Load the submodules */
  7. import project from './project/route'
  8. /** Create the express app */
  9. const app = express()
  10. /** MongoDB middleware */
  11. const dbName = 'movieDB'
  12. const connectionString = `mongodb://localhost:27017/${dbName}`
  13. /** Sockjs middleware */
  14. const sockjsOpts = {sockjs_url: 'http://cdn.jsdelivr.net/sockjs/1.0.1/sockjs.min.js'}
  15. const sockjsServer = sockjs.createServer(sockjsOpts)
  16. sockjsServer.on('connection', function (conn) {
  17. conn.on('data', function (message) {
  18. conn.write(message)
  19. })
  20. })
  21. /** Bind the http server to express */
  22. const server = http.createServer(app)
  23. sockjsServer.installHandlers(server, {prefix: '/echo'})
  24. mongoose.connect(connectionString)
  25. function welcomeRouter (req, res) {
  26. res.json({ message: 'Welcome to the AutoMate db API!' })
  27. }
  28. function errorRouter (req, res) {
  29. res.status(404)
  30. res.send({ message: 'Unknown route.' })
  31. }
  32. app.use(bodyParser.json())
  33. app.use(bodyParser.urlencoded({ extended: true }))
  34. app.get(/^\/db\/?$/, welcomeRouter)
  35. app.get(/^\/db(\/\w+)?(\/\w+)?\/?$/, [project.get])
  36. app.post(/^\/db(\/\w+)?(\/\w+)?\/?$/, [project.post])
  37. app.put(/^\/db(\/\w+)?(\/\w+)?\/?$/, [project.put])
  38. app.delete(/^\/db(\/\w+)?(\/\w+)?\/?$/, [project.delete])
  39. app.use(/.*/, errorRouter)
  40. /* app.get('/', function (req, res) {
  41. res.sendFile(`${__dirname}/index.html`)
  42. }) */
  43. server.listen(process.env.PORT || 4000)