server.js 1.2 KB

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