server.js 1.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849
  1. const express = require('express')
  2. const C = require('./controllers')
  3. const config = require('../config')
  4. const path = require('path')
  5. const chalk = require('chalk')
  6. const asyncHandler = require('express-async-handler')
  7. const bodyParser = require('body-parser')
  8. const routes = require('./routes')
  9. const serverFactory = require('../auto-crud/server-factory')
  10. const app = express()
  11. app.use(C.auth.decode)
  12. app.use(bodyParser.json())
  13. routes(app)
  14. serverFactory(app)
  15. app.start = () => new Promise((resolve, reject) => {
  16. app.use(express.static('./public'))
  17. app.all('/api/*', (req, res) => {
  18. res.send(404)
  19. })
  20. app.get('*', (req, res) => {
  21. res.sendFile(path.join(process.cwd(), 'public/index.html'));
  22. })
  23. try {
  24. const listener = app.listen(config.server.port, function() {
  25. app.address = listener.address()
  26. console.log(`Server running at ${chalk.underline(chalk.blue(`http://localhost:${app.address.port}`))}`)
  27. })
  28. } catch (e) {
  29. reject(e)
  30. }
  31. })
  32. const asyncWrap = (method) => (function() {
  33. const args = Array.from(arguments)
  34. if (args[1]) args[1] = asyncHandler(args[1])
  35. return method.apply(app, args)
  36. })
  37. const asyncApp = Object.assign(Object.create(app), {
  38. get: asyncWrap(app.get),
  39. post: asyncWrap(app.post),
  40. put: asyncWrap(app.put),
  41. patch: asyncWrap(app.patch),
  42. delete: asyncWrap(app.delete)
  43. })
  44. module.exports = asyncApp