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.

150 lines
3.9 KiB

9 years ago
9 years ago
9 years ago
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. const conditional = require('koa-conditional-get');
  12. const etag = require('koa-etag');
  13. const _ = require('koa-route')
  14. const mount = require('koa-mount')
  15. const httpProxy = require('http-proxy')
  16. const pathToRegexp = require('path-to-regexp')
  17. const http = require('http')
  18. /**
  19. * @module local-web-server
  20. */
  21. module.exports = getApp
  22. function getApp (options) {
  23. options = Object.assign({
  24. static: {},
  25. serveIndex: {},
  26. log: {},
  27. compress: false,
  28. blacklist: [],
  29. directories: [],
  30. proxyRoutes: []
  31. }, options)
  32. const log = options.log
  33. log.options = log.options || {}
  34. const app = new Koa()
  35. const _use = app.use
  36. app.use = x => _use.call(app, convert(x))
  37. const proxy = httpProxy.createProxyServer({
  38. changeOrigin: true
  39. })
  40. /* Proxy routes */
  41. options.proxyRoutes.forEach(route => {
  42. app.use(_.all(route.from, function * () {
  43. const keys = []
  44. route.re = pathToRegexp(route.from, keys)
  45. route.new = route.to
  46. this.response = false
  47. keys.forEach((key, index) => {
  48. const re = {
  49. token: RegExp('\\$\\{' + key.name + '\\}', 'g'),
  50. index: RegExp('\\$\\{' + index + '\\}', 'g')
  51. }
  52. route.new = route.new
  53. .replace(re.token, arguments[index] || '')
  54. .replace(re.index, arguments[index] || '')
  55. })
  56. proxy.once('proxyReq', function (proxyReq) {
  57. proxyReq.path = route.new;
  58. })
  59. proxy.web(this.req, this.res, { target: route.new })
  60. }))
  61. })
  62. /* CORS: allow from any origin */
  63. app.use(cors())
  64. /* path blacklist */
  65. if (options.blacklist.length) {
  66. app.use(function pathBlacklist (ctx, next) {
  67. if (options.blacklist.some(regexp => regexp.test(ctx.path))) {
  68. ctx.throw(403, http.STATUS_CODES[403])
  69. } else {
  70. return next()
  71. }
  72. })
  73. }
  74. app.use(conditional())
  75. app.use(etag())
  76. /* mime-type overrides */
  77. if (options.mime) {
  78. app.use((ctx, next) => {
  79. return next().then(() => {
  80. const reqPathExtension = path.extname(ctx.path).slice(1)
  81. Object.keys(options.mime).forEach(mimeType => {
  82. const extsToOverride = options.mime[mimeType]
  83. if (extsToOverride.indexOf(reqPathExtension) > -1) ctx.type = mimeType
  84. })
  85. })
  86. })
  87. }
  88. /* compress response */
  89. if (options.compress) {
  90. app.use(compress())
  91. }
  92. /* special case log formats */
  93. if (log.format) {
  94. if (log.format === 'none'){
  95. log.format = undefined
  96. } else if (log.format === 'logstalgia') {
  97. morgan.token('date', logstalgiaDate)
  98. log.format = 'combined'
  99. }
  100. /* if no specific log format was requested, show log stats */
  101. } else {
  102. log.format = 'common'
  103. log.options.stream = streamLogStats({ refreshRate: 500 })
  104. }
  105. if (log.format) app.use(morgan.middleware(log.format, log.options))
  106. // options.static.root = [
  107. // { route: '/one', root: 'lib' },
  108. // { route: '/two', root: 'node_modules' }
  109. // ]
  110. /* serve static files */
  111. if (options.static.root) {
  112. app.use(serve(options.static.root, options.static.options))
  113. // options.static.root.forEach(config => {
  114. // app.use(mount(config.route, serve(config.root)))
  115. // app.use(mount(config.route, serveIndex(config.root)))
  116. // })
  117. }
  118. /* serve directory index */
  119. if (options.serveIndex.path) {
  120. app.use(serveIndex(options.serveIndex.path, options.serveIndex.options))
  121. }
  122. return app
  123. }
  124. function logstalgiaDate () {
  125. var d = new Date()
  126. return (`${d.getDate()}/${d.getUTCMonth()}/${d.getFullYear()}:${d.toTimeString()}`)
  127. .replace('GMT', '')
  128. .replace(' (BST)', '')
  129. }
  130. process.on('unhandledRejection', (reason, p) => {
  131. throw reason
  132. })