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.

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