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.

82 lines
2.0 KiB

  1. 'use strict'
  2. const path = require('path')
  3. const Koa = require('koa')
  4. const serve = require('koa-static')
  5. const convert = require('koa-convert')
  6. const serveIndex = require('koa-serve-index')
  7. const morgan = require('koa-morgan')
  8. const compress = require('koa-compress')
  9. const streamLogStats = require('stream-log-stats')
  10. /**
  11. * @module local-web-server
  12. */
  13. module.exports = getApp
  14. process.on('unhandledRejection', (reason, p) => {
  15. throw reason
  16. })
  17. function getApp (options) {
  18. options = Object.assign({
  19. static: {},
  20. serveIndex: {},
  21. log: {},
  22. compress: false
  23. }, options)
  24. const log = options.log
  25. log.options = log.options || {}
  26. const app = new Koa()
  27. // CORS
  28. if (options.mime) {
  29. app.use((ctx, next) => {
  30. return next().then(() => {
  31. const reqPathExtension = path.extname(ctx.path).slice(1)
  32. Object.keys(options.mime).forEach(mimeType => {
  33. const extsToOverride = options.mime[mimeType]
  34. if (extsToOverride.indexOf(reqPathExtension) > -1) ctx.type = mimeType
  35. })
  36. })
  37. })
  38. }
  39. if (options.compress) {
  40. app.use(convert(compress()))
  41. }
  42. /* special case log formats */
  43. if (log.format) {
  44. if (log.format === 'none'){
  45. log.format = undefined
  46. } else if (log.format === 'logstalgia') {
  47. morgan.token('date', logstalgiaDate)
  48. log.format = 'combined'
  49. }
  50. /* if no specific log format was requested, show log stats */
  51. } else {
  52. log.format = 'common'
  53. log.options.stream = streamLogStats({ refreshRate: 500 })
  54. }
  55. if (log.format) app.use(convert(morgan.middleware(log.format, log.options)))
  56. if (options.static.root) {
  57. app.use(convert(serve(options.static.root, options.static.options)))
  58. }
  59. if (options.serveIndex.path) {
  60. app.use(convert(serveIndex(options.serveIndex.path, options.serveIndex.options)))
  61. }
  62. return app
  63. }
  64. function logstalgiaDate () {
  65. var d = new Date()
  66. return (`${d.getDate()}/${d.getUTCMonth()}/${d.getFullYear()}:${d.toTimeString()}`)
  67. .replace('GMT', '')
  68. .replace(' (BST)', '')
  69. }