docs.. examples.. tests

This commit is contained in:
Lloyd Brookes
2015-11-17 15:13:22 +00:00
parent f88766e460
commit b50697186e
11 changed files with 80 additions and 62 deletions

View File

@ -17,7 +17,14 @@ module.exports = localWebServer
* Returns a Koa application
*
* @param [options] {object} - options
* @param [options.forbid] {regexp[]} - a list of forbidden routes.
* @param [options.static] {object} - koajs/static config
* @param [options.static.root] {string} - root directory
* @param [options.static.options] {string} - options
* @param [options.serveIndex] {object} - koa-serve-index config
* @param [options.serveIndex.path] {string} - root directory
* @param [options.serveIndex.options] {string} - options
* @param [options.forbid] {string[]} - a list of forbidden routes.
*
* @alias module:local-web-server
* @example
* const localWebServer = require('local-web-server')
@ -29,6 +36,7 @@ function localWebServer (options) {
serveIndex: {},
log: {},
compress: false,
mime: {},
forbid: [],
rewrite: []
}, options)
@ -138,35 +146,35 @@ function proxyRequest (route) {
changeOrigin: true
})
return function * proxyMiddleware () {
const next = arguments[arguments.length-1]
return function proxyMiddleware (ctx) {
const next = arguments[arguments.length - 1]
const keys = []
route.re = pathToRegexp(route.from, keys)
route.new = this.path.replace(route.re, route.to)
route.new = ctx.path.replace(route.re, route.to)
keys.forEach((key, index) => {
const re = RegExp(`:${key.name}`, 'g')
route.new = route.new
.replace(re, arguments[index] || '')
.replace(re, arguments[index + 1] || '')
})
/* test no keys remain in the new path */
keys.length = 0
pathToRegexp(route.new, keys)
if (keys.length) {
this.throw(500, `[PROXY] Invalid target URL: ${route.new}`)
yield next
ctx.throw(500, `[PROXY] Invalid target URL: ${route.new}`)
return next()
}
this.response = false
ctx.response = false
proxy.once('error', err => {
this.throw(500, `[PROXY] ${err.message}: ${route.new}`)
ctx.throw(500, `[PROXY] ${err.message}: ${route.new}`)
})
proxy.once('proxyReq', function (proxyReq) {
proxyReq.path = url.parse(route.new).path;
})
proxy.web(this.req, this.res, { target: route.new })
proxy.web(ctx.req, ctx.res, { target: route.new })
}
}