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.

84 lines
2.1 KiB

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