Browse Source

rewrite and examples.. refactor

master
Lloyd Brookes 9 years ago
parent
commit
89b427e1fa
  1. 4
      bin/cli.js
  2. 8
      example/rewrite/.local-web-server.json
  3. 26
      example/rewrite/index.html
  4. 7
      example/rewrite/styles/style.css
  5. 6
      jsdoc2md/README.hbs
  6. 110
      lib/local-web-server.js
  7. 1
      package.json

4
bin/cli.js

@ -40,7 +40,7 @@ localWebServer({
log: { format: options.server['log-format'] }, log: { format: options.server['log-format'] },
compress: options.server.compress, compress: options.server.compress,
mime: options.server.mime, mime: options.server.mime,
forbid: options.server.forbid.map(regexp => RegExp(regexp, "i")),
forbid: options.server.forbid.map(regexp => RegExp(regexp, 'i')),
proxyRoutes: options.server.proxyRoutes, proxyRoutes: options.server.proxyRoutes,
spa: options.server.spa, spa: options.server.spa,
'no-cache': options.server['no-cache'], 'no-cache': options.server['no-cache'],
@ -55,7 +55,7 @@ function halt (err) {
function onServerUp () { function onServerUp () {
const e = Date.now() const e = Date.now()
const time = `${e-s}ms`
const time = `${e - s}ms`
console.error(ansi.format( console.error(ansi.format(
path.resolve(options.server.directory) === process.cwd() path.resolve(options.server.directory) === process.cwd()
? `serving at [underline]{http://localhost:${options.server.port}} ${time}` ? `serving at [underline]{http://localhost:${options.server.port}} ${time}`

8
example/rewrite/.local-web-server.json

@ -1,5 +1,7 @@
{ {
"rewrite": [
{ "from": "/css/*", "to": "/styles/$1" }
]
"rewrite": [
{ "from": "/css/*", "to": "/styles/$1" },
{ "from": "/npm/*", "to": "http://registry.npmjs.org/$1" },
{ "from": "/gh/:user/repo/:name", "to": "https://api.github.com/repos/:user/:name" }
]
} }

26
example/rewrite/index.html

@ -1,10 +1,22 @@
<head> <head>
<link rel="stylesheet" href="css/style.css"> <link rel="stylesheet" href="css/style.css">
</head> </head>
<h1>Amazing Page</h1>
<p>
With a freaky triangle..
</p>
<svg width="500" height="500">
<polygon points="250,0 0,500 500,500"></polygon>
</svg>
<h1>Rewriting paths</h1>
<h2>Config</h2>
<pre><code>
{
"rewrite": [
{ "from": "/css/*", "to": "/styles/$1" },
{ "from": "/npm/*", "to": "http://registry.npmjs.org/$1" },
{ "from": "/gh/:user/repo/:name", "to": "https://api.github.com/repos/:user/:name" }
]
}
</code></pre>
<h2>Links</h2>
<ul>
<li><a href="/css/style.css">/css/style.css</li>
<li><a href="/npm/local-web-server">/npm/local-web-server</a></li>
<li><a href="/gh/75lb/repo/work">/gh/75lb/repo/work</a></li>
</ul>

7
example/rewrite/styles/style.css

@ -1,7 +1,4 @@
body { body {
background-color: #AA3939;
color: #FFE2E2
}
svg {
fill: #000
font-family: monospace;
font-size: 1.3em;
} }

6
jsdoc2md/README.hbs

@ -35,9 +35,9 @@ You're building a web app with client-side routing, so mark `index.html` as the
$ ws --spa index.html $ ws --spa index.html
``` ```
By default, typical SPA urls (e.g. `/user/1`, `/login`) would return `404 Not Found` as there is no file at that location on disk. By marking `index.html` as the SPA you create this rule:
By default, typical SPA urls (e.g. `/user/1`, `/login`) would return `404 Not Found` as a file does not exist with that path. By marking `index.html` as the SPA you create this rule:
*if a static file at the requested path exists (e.g. `/css/style.css`) then serve it, if it does not (e.g. `/login`) then serve the SPA.*
*If a static file at the requested path exists (e.g. `/css/style.css`) then serve it, if it does not (e.g. `/login`) then serve the SPA for client-side processing.*
### Access Control ### Access Control
@ -54,7 +54,7 @@ When urls don't map to your directory structure, rewrite:
$ ws --rewrite /css=>/build/css $ ws --rewrite /css=>/build/css
``` ```
### Proxy
### Proxy to external services
Rewrite to remote servers (proxy): Rewrite to remote servers (proxy):
```sh ```sh

110
lib/local-web-server.js

@ -6,7 +6,6 @@ const Koa = require('koa')
const convert = require('koa-convert') const convert = require('koa-convert')
const cors = require('kcors') const cors = require('kcors')
const _ = require('koa-route') const _ = require('koa-route')
const mount = require('koa-mount')
const pathToRegexp = require('path-to-regexp') const pathToRegexp = require('path-to-regexp')
/** /**
@ -43,63 +42,32 @@ function localWebServer (options) {
const _use = app.use const _use = app.use
app.use = x => _use.call(app, convert(x)) app.use = x => _use.call(app, convert(x))
/* CORS: allow from any origin */
app.use(cors())
/* Proxy routes */
if (options.proxyRoutes.length) {
const httpProxy = require('http-proxy')
const proxy = httpProxy.createProxyServer({
changeOrigin: true
})
options.proxyRoutes.forEach(route => {
app.use(_.all(route.from, function * () {
const keys = []
route.re = pathToRegexp(route.from, keys)
route.new = route.to
this.response = false
keys.forEach((key, index) => {
const re = {
token: RegExp('\\$\\{' + key.name + '\\}', 'g'),
index: RegExp('\\$\\{' + index + '\\}', 'g')
}
route.new = route.new
.replace(re.token, arguments[index] || '')
.replace(re.index, arguments[index] || '')
})
proxy.once('proxyReq', function (proxyReq) {
proxyReq.path = url.parse(route.new).path;
})
proxy.web(this.req, this.res, { target: route.new })
}))
})
}
/* Rewrite rules */
/* rewrite rules */
if (options.rewrite && options.rewrite.length) { if (options.rewrite && options.rewrite.length) {
const rewrite = require('koa-rewrite')
options.rewrite.forEach(rule => {
app.use(rewrite(rule.from, rule.to))
options.rewrite.forEach(route => {
if (route.to) {
if (url.parse(route.to).host) {
app.use(_.all(route.from, proxyRequest(route)))
} else {
const rewrite = require('koa-rewrite')
app.use(rewrite(route.from, route.to))
}
}
}) })
} }
/* CORS: allow from any origin */
app.use(cors())
/* path blacklist */ /* path blacklist */
if (options.forbid.length) { if (options.forbid.length) {
app.use(function blacklist (ctx, next) {
if (options.forbid.some(regexp => regexp.test(ctx.path))) {
ctx.throw(403, http.STATUS_CODES[403])
} else {
return next()
}
})
app.use(blacklist(options.forbid))
} }
/* Cache */ /* Cache */
if (!options['no-cache']) { if (!options['no-cache']) {
const conditional = require('koa-conditional-get');
const etag = require('koa-etag');
const conditional = require('koa-conditional-get')
const etag = require('koa-etag')
app.use(conditional()) app.use(conditional())
app.use(etag()) app.use(etag())
} }
@ -168,6 +136,54 @@ function logstalgiaDate () {
.replace(' (BST)', '') .replace(' (BST)', '')
} }
function proxyRequest (route) {
const httpProxy = require('http-proxy')
const proxy = httpProxy.createProxyServer({
changeOrigin: true
})
return function * proxyMiddleware () {
const next = arguments[arguments.length-1]
const keys = []
route.re = pathToRegexp(route.from, keys)
route.new = this.path.replace(route.re, route.to)
keys.forEach((key, index) => {
const re = RegExp(`:${key.name}`, 'g')
route.new = route.new
.replace(re, arguments[index] || '')
})
/* 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
}
this.response = false
proxy.once('error', err => {
this.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 })
}
}
function blacklist (forbid) {
return function blacklist (ctx, next) {
if (forbid.some(regexp => regexp.test(ctx.path))) {
ctx.throw(403, http.STATUS_CODES[403])
} else {
return next()
}
}
}
process.on('unhandledRejection', (reason, p) => { process.on('unhandledRejection', (reason, p) => {
throw reason throw reason
}) })

1
package.json

@ -38,7 +38,6 @@
"koa-convert": "^1.1.0", "koa-convert": "^1.1.0",
"koa-etag": "^2.1.0", "koa-etag": "^2.1.0",
"koa-morgan": "^0.4.0", "koa-morgan": "^0.4.0",
"koa-mount": "^1.3.0",
"koa-rewrite": "^1.1.1", "koa-rewrite": "^1.1.1",
"koa-route": "^2.4.2", "koa-route": "^2.4.2",
"koa-send": "^3.1.0", "koa-send": "^3.1.0",

Loading…
Cancel
Save