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.

115 lines
3.2 KiB

9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
8 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
8 years ago
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 http = require('http')
  4. const url = require('url')
  5. const arrayify = require('array-back')
  6. const t = require('typical')
  7. const pathToRegexp = require('path-to-regexp')
  8. const debug = require('debug')('local-web-server')
  9. /**
  10. * @module middleware
  11. */
  12. exports.proxyRequest = proxyRequest
  13. exports.blacklist = blacklist
  14. exports.mockResponses = mockResponses
  15. exports.mime = mime
  16. function proxyRequest (route) {
  17. const httpProxy = require('http-proxy')
  18. const proxy = httpProxy.createProxyServer({
  19. changeOrigin: true,
  20. secure: false
  21. })
  22. proxy.on('error', err => {
  23. // not worth crashing for
  24. })
  25. return function proxyMiddleware () {
  26. const keys = []
  27. route.re = pathToRegexp(route.from, keys)
  28. route.new = this.url.replace(route.re, route.to)
  29. keys.forEach((key, index) => {
  30. const re = RegExp(`:${key.name}`, 'g')
  31. route.new = route.new
  32. .replace(re, arguments[index + 1] || '')
  33. })
  34. debug('proxy request', `from: ${this.path}, to: ${url.parse(route.new).href}`)
  35. return new Promise((resolve, reject) => {
  36. proxy.once('error', err => {
  37. err.message = `[PROXY] Error: ${err.message} Target: ${route.new}`
  38. reject(err)
  39. })
  40. proxy.once('proxyReq', function (proxyReq) {
  41. proxyReq.path = url.parse(route.new).path
  42. })
  43. proxy.once('close', resolve)
  44. proxy.web(this.req, this.res, { target: route.new })
  45. })
  46. }
  47. }
  48. function blacklist (forbid) {
  49. return function blacklist (ctx, next) {
  50. if (forbid.some(expression => pathToRegexp(expression).test(ctx.path))) {
  51. ctx.throw(403, http.STATUS_CODES[403])
  52. } else {
  53. return next()
  54. }
  55. }
  56. }
  57. function mime (mimeTypes) {
  58. return function mime (ctx, next) {
  59. return next().then(() => {
  60. const reqPathExtension = path.extname(ctx.path).slice(1)
  61. Object.keys(mimeTypes).forEach(mimeType => {
  62. const extsToOverride = mimeTypes[mimeType]
  63. if (extsToOverride.indexOf(reqPathExtension) > -1) ctx.type = mimeType
  64. })
  65. })
  66. }
  67. }
  68. function mockResponses (route, targets) {
  69. targets = arrayify(targets)
  70. debug('mock route: %s, targets: %s', route, targets.length)
  71. const pathRe = pathToRegexp(route)
  72. return function mockResponse (ctx, next) {
  73. if (pathRe.test(ctx.path)) {
  74. const testValue = require('test-value')
  75. /* find a mock with compatible method and accepts */
  76. let target = targets.find(target => {
  77. return testValue(target, {
  78. request: {
  79. method: [ ctx.method, undefined ],
  80. accepts: type => ctx.accepts(type)
  81. }
  82. })
  83. })
  84. /* else take the first target without a request (no request means 'all requests') */
  85. if (!target) {
  86. target = targets.find(target => !target.request)
  87. }
  88. if (target) {
  89. if (t.isFunction(target.response)) {
  90. const pathMatches = ctx.path.match(pathRe).slice(1)
  91. return target.response.apply(null, [ctx].concat(pathMatches))
  92. } else if (t.isPlainObject(target.response)) {
  93. Object.assign(ctx.response, target.response)
  94. } else {
  95. throw new Error(`Invalid response: ${JSON.stringify(target.response)}`)
  96. }
  97. }
  98. } else {
  99. return next()
  100. }
  101. }
  102. }