server.js 1.3 KB

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