You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

66 lines
1.8 KiB

  1. 'use strict'
  2. const Koa = require('koa')
  3. const serve = require('koa-static')
  4. const convert = require('koa-convert')
  5. const serveIndex = require('koa-serve-index')
  6. const morgan = require('koa-morgan')
  7. const compress = require('koa-compress')
  8. const streamLogStats = require('stream-log-stats')
  9. /**
  10. * @module local-web-server
  11. */
  12. module.exports = getApp
  13. process.on('unhandledRejection', (reason, p) => {
  14. throw reason
  15. })
  16. function getApp (options) {
  17. options = Object.assign({
  18. static: {},
  19. serveIndex: {},
  20. logger: {},
  21. compress: false
  22. }, options)
  23. const app = new Koa()
  24. if (options.compress) {
  25. console.log('comp');
  26. app.use(convert(compress()))
  27. }
  28. let log = { format: options.logger.format }
  29. if (options.logger.format) {
  30. if (log.format === 'none'){
  31. log.format = undefined
  32. } else if (log.format === 'logstalgia') {
  33. /* customised logger :date token, purely to satisfy Logstalgia. */
  34. morgan.token('date', function () {
  35. var d = new Date()
  36. return (d.getDate() + '/' + d.getUTCMonth() + '/' + d.getFullYear() + ':' + d.toTimeString())
  37. .replace('GMT', '').replace(' (BST)', '')
  38. })
  39. log.format = 'combined'
  40. } else if (log.format) {
  41. log.stream = process.stdout
  42. }
  43. } else {
  44. log.format = 'common'
  45. log.stream = streamLogStats({ refreshRate: 100 })
  46. }
  47. options.logger.options = options.logger.options || {}
  48. options.logger.options.stream = log.stream
  49. if (log.format) app.use(convert(morgan.middleware(log.format, options.logger.options)))
  50. if (options.static.root) {
  51. app.use(convert(serve(options.static.root, options.static.options)))
  52. }
  53. if (options.serveIndex.path) {
  54. app.use(convert(serveIndex(options.serveIndex.path, options.serveIndex.options)))
  55. }
  56. return app
  57. }