Files
hiring-test-one/lib/local-web-server.js

311 lines
9.2 KiB
JavaScript
Raw Normal View History

2015-11-08 22:09:07 +00:00
'use strict'
2015-11-13 11:26:02 +00:00
const path = require('path')
2015-11-15 13:53:27 +00:00
const http = require('http')
const url = require('url')
2015-11-18 16:37:16 +00:00
const arrayify = require('array-back')
2015-11-19 16:03:01 +00:00
let debug, pathToRegexp
2015-11-08 22:09:07 +00:00
/**
* @module local-web-server
*/
2015-11-15 21:15:25 +00:00
module.exports = localWebServer
2015-11-08 22:09:07 +00:00
2015-11-15 21:15:25 +00:00
/**
* Returns a Koa application you can launch or mix into an existing app.
2015-11-15 21:15:25 +00:00
*
* @param [options] {object} - options
2015-11-19 10:01:04 +00:00
* @param [options.static] {object} - koa-static config
2015-11-17 15:13:22 +00:00
* @param [options.static.root] {string} - root directory
2015-11-19 10:01:04 +00:00
* @param [options.static.options] {string} - [options](https://github.com/koajs/static#options)
2015-11-17 15:13:22 +00:00
* @param [options.serveIndex] {object} - koa-serve-index config
* @param [options.serveIndex.path] {string} - root directory
2015-11-19 10:01:04 +00:00
* @param [options.serveIndex.options] {string} - [options](https://github.com/expressjs/serve-index#options)
* @param [options.forbid] {string[]} - A list of forbidden routes, each route being an [express route-path](http://expressjs.com/guide/routing.html#route-paths).
* @param [options.spa] {string} - specify an SPA file to catch requests for everything but static assets.
* @param [options.log] {object} - [morgan](https://github.com/expressjs/morgan) config
* @param [options.log.format] {string} - [log format](https://github.com/expressjs/morgan#predefined-formats)
* @param [options.log.options] {object} - [options](https://github.com/expressjs/morgan#options)
* @param [options.compress] {boolean} - Serve gzip-compressed resources, where applicable
* @param [options.mime] {object} - A list of mime-type overrides, passed directly to [mime.define()](https://github.com/broofa/node-mime#mimedefine)
* @param [options.rewrite] {module:local-web-server~rewriteRule[]} - One or more rewrite rules
* @param [options.verbose] {boolean} - Print detailed output, useful for debugging
2015-11-17 15:13:22 +00:00
*
2015-11-15 21:15:25 +00:00
* @alias module:local-web-server
2015-11-19 10:17:02 +00:00
* @return {external:KoaApplication}
2015-11-15 21:15:25 +00:00
* @example
* const localWebServer = require('local-web-server')
2015-11-16 13:22:51 +00:00
* localWebServer().listen(8000)
2015-11-15 21:15:25 +00:00
*/
function localWebServer (options) {
2015-11-10 21:50:56 +00:00
options = Object.assign({
static: {},
serveIndex: {},
2015-11-17 16:01:17 +00:00
spa: null,
log: {},
2015-11-13 19:55:52 +00:00
compress: false,
2015-11-17 15:13:22 +00:00
mime: {},
forbid: [],
rewrite: [],
verbose: false
2015-11-08 22:09:07 +00:00
}, options)
2015-11-18 16:37:16 +00:00
if (options.verbose) {
process.env.DEBUG = '*'
}
const Koa = require('koa')
const convert = require('koa-convert')
const cors = require('kcors')
const _ = require('koa-route')
2015-11-19 17:48:31 +00:00
const json = require('koa-json')
2015-11-19 16:03:01 +00:00
pathToRegexp = require('path-to-regexp')
2015-11-18 16:37:16 +00:00
debug = require('debug')('local-web-server')
2015-11-19 17:48:31 +00:00
const bodyParser = require('koa-bodyparser')
2015-11-18 16:37:16 +00:00
const log = options.log
log.options = log.options || {}
2015-11-08 22:09:07 +00:00
const app = new Koa()
2015-11-15 11:59:45 +00:00
const _use = app.use
app.use = x => _use.call(app, convert(x))
2015-11-18 16:37:16 +00:00
function verbose (category, message) {
if (options.verbose) {
2015-11-18 16:37:16 +00:00
debug(category, message)
}
}
app._verbose = verbose
if (options.verbose && !log.format) {
log.format = 'none'
}
2015-11-15 11:59:45 +00:00
2015-11-16 20:47:34 +00:00
/* CORS: allow from any origin */
app.use(cors())
2015-11-15 11:59:45 +00:00
2015-11-19 17:48:31 +00:00
/* pretty print JSON */
app.use(json())
/* request body parser */
app.use(bodyParser())
2015-11-16 20:47:34 +00:00
/* rewrite rules */
2015-11-16 13:22:51 +00:00
if (options.rewrite && options.rewrite.length) {
2015-11-16 20:47:34 +00:00
options.rewrite.forEach(route => {
if (route.to) {
if (url.parse(route.to).host) {
verbose('proxy rewrite', `${route.from} -> ${route.to}`)
app.use(_.all(route.from, proxyRequest(route, app)))
2015-11-16 20:47:34 +00:00
} else {
const rewrite = require('koa-rewrite')
2015-11-19 16:03:01 +00:00
const mw = rewrite(route.from, route.to)
mw._name = 'rewrite'
app.use(mw)
2015-11-16 20:47:34 +00:00
}
}
2015-11-16 13:22:51 +00:00
})
}
2015-11-08 22:09:07 +00:00
2015-11-13 15:33:19 +00:00
/* path blacklist */
if (options.forbid.length) {
verbose('forbid', options.forbid.join(', '))
2015-11-16 20:47:34 +00:00
app.use(blacklist(options.forbid))
2015-11-13 19:55:52 +00:00
}
2015-11-13 15:33:19 +00:00
2015-11-15 15:51:18 +00:00
/* Cache */
if (!options['no-cache']) {
2015-11-16 20:47:34 +00:00
const conditional = require('koa-conditional-get')
const etag = require('koa-etag')
2015-11-15 15:51:18 +00:00
app.use(conditional())
app.use(etag())
}
2015-11-13 15:33:19 +00:00
/* mime-type overrides */
2015-11-13 11:26:02 +00:00
if (options.mime) {
verbose('mime override', JSON.stringify(options.mime))
2015-11-13 11:26:02 +00:00
app.use((ctx, next) => {
return next().then(() => {
const reqPathExtension = path.extname(ctx.path).slice(1)
Object.keys(options.mime).forEach(mimeType => {
const extsToOverride = options.mime[mimeType]
if (extsToOverride.indexOf(reqPathExtension) > -1) ctx.type = mimeType
})
})
})
}
2015-11-13 15:33:19 +00:00
/* compress response */
2015-11-12 23:02:38 +00:00
if (options.compress) {
2015-11-16 13:22:51 +00:00
const compress = require('koa-compress')
verbose('compression', 'enabled')
2015-11-15 11:59:45 +00:00
app.use(compress())
2015-11-12 23:02:38 +00:00
}
2015-11-16 13:22:51 +00:00
/* Logging */
if (log.format !== 'none') {
const morgan = require('koa-morgan')
if (!log.format) {
const streamLogStats = require('stream-log-stats')
log.options.stream = streamLogStats({ refreshRate: 500 })
app.use(morgan.middleware('common', log.options))
2015-11-12 23:02:38 +00:00
} else if (log.format === 'logstalgia') {
morgan.token('date', logstalgiaDate)
2015-11-16 13:22:51 +00:00
app.use(morgan.middleware('combined', log.options))
} else {
app.use(morgan.middleware(log.format, log.options))
2015-11-12 23:02:38 +00:00
}
2015-11-10 21:50:56 +00:00
}
2015-11-12 23:02:38 +00:00
2015-11-18 16:37:16 +00:00
/* Mock Responses */
app.use(mockResponses({ root: options.static.root, verbose: verbose }))
2015-11-13 15:33:19 +00:00
/* serve static files */
2015-11-10 21:50:56 +00:00
if (options.static.root) {
2015-11-16 13:22:51 +00:00
const serve = require('koa-static')
2015-11-15 11:59:45 +00:00
app.use(serve(options.static.root, options.static.options))
2015-11-10 21:50:56 +00:00
}
2015-11-13 15:33:19 +00:00
/* serve directory index */
2015-11-10 21:50:56 +00:00
if (options.serveIndex.path) {
2015-11-16 13:22:51 +00:00
const serveIndex = require('koa-serve-index')
2015-11-15 11:59:45 +00:00
app.use(serveIndex(options.serveIndex.path, options.serveIndex.options))
2015-11-10 21:50:56 +00:00
}
2015-11-12 23:02:38 +00:00
2015-11-15 14:53:25 +00:00
/* for any URL not matched by static (e.g. `/search`), serve the SPA */
if (options.spa) {
2015-11-16 13:22:51 +00:00
const send = require('koa-send')
verbose('SPA', options.spa)
2015-11-15 14:53:25 +00:00
app.use(_.all('*', function * () {
2015-11-17 16:44:14 +00:00
yield send(this, options.spa, { root: path.resolve(options.static.root) || process.cwd() })
2015-11-15 14:53:25 +00:00
}))
}
2015-11-08 22:09:07 +00:00
return app
}
function logstalgiaDate () {
var d = new Date()
return (`${d.getDate()}/${d.getUTCMonth()}/${d.getFullYear()}:${d.toTimeString()}`).replace('GMT', '').replace(' (BST)', '')
}
2015-11-13 15:33:19 +00:00
function proxyRequest (route, app) {
2015-11-16 20:47:34 +00:00
const httpProxy = require('http-proxy')
const proxy = httpProxy.createProxyServer({
changeOrigin: true
})
2015-11-17 16:01:17 +00:00
return function * proxyMiddleware () {
2015-11-17 15:13:22 +00:00
const next = arguments[arguments.length - 1]
2015-11-16 20:47:34 +00:00
const keys = []
route.re = pathToRegexp(route.from, keys)
route.new = this.url.replace(route.re, route.to)
2015-11-16 20:47:34 +00:00
keys.forEach((key, index) => {
const re = RegExp(`:${key.name}`, 'g')
route.new = route.new
2015-11-17 16:01:17 +00:00
.replace(re, arguments[index] || '')
2015-11-16 20:47:34 +00:00
})
/* test no keys remain in the new path */
keys.length = 0
pathToRegexp(url.parse(route.new).path, keys)
2015-11-16 20:47:34 +00:00
if (keys.length) {
2015-11-17 16:01:17 +00:00
this.throw(500, `[PROXY] Invalid target URL: ${route.new}`)
2015-11-17 15:13:22 +00:00
return next()
2015-11-16 20:47:34 +00:00
}
2015-11-17 16:01:17 +00:00
this.response = false
app._verbose('proxy request', `from: ${this.path}, to: ${url.parse(route.new).href}`)
2015-11-16 20:47:34 +00:00
proxy.once('error', err => {
2015-11-17 16:01:17 +00:00
this.throw(500, `[PROXY] ${err.message}: ${route.new}`)
2015-11-16 20:47:34 +00:00
})
proxy.once('proxyReq', function (proxyReq) {
proxyReq.path = url.parse(route.new).path
2015-11-16 20:47:34 +00:00
})
2015-11-17 16:01:17 +00:00
proxy.web(this.req, this.res, { target: route.new })
2015-11-16 20:47:34 +00:00
}
}
function blacklist (forbid) {
return function blacklist (ctx, next) {
if (forbid.some(expression => pathToRegexp(expression).test(ctx.path))) {
2015-11-16 20:47:34 +00:00
ctx.throw(403, http.STATUS_CODES[403])
} else {
return next()
}
}
}
2015-11-18 16:37:16 +00:00
function mockResponses (options) {
options = options || { root: process.cwd() }
return function mockResponses (ctx, next) {
if (/\.mock.js$/.test(ctx.path)) {
const mocks = arrayify(require(path.join(options.root, ctx.path)))
2015-11-19 16:03:01 +00:00
const testValue = require('test-value')
const t = require('typical')
/* find a mock with compatible method and accepts */
let mock = mocks.find(mock => {
return testValue(mock, {
request: {
method: [ ctx.method, undefined ],
accepts: type => ctx.accepts(type)
}
})
2015-11-18 16:37:16 +00:00
})
2015-11-19 16:03:01 +00:00
/* else take the first mock without a request (no request means 'all requests') */
if (!mock) {
mock = mocks.find(mock => !mock.request)
}
const mockedReponse = {}
/* resolve any functions on the mock */
Object.keys(mock.response).forEach(key => {
if (t.isFunction(mock.response[key])) {
mockedReponse[key] = mock.response[key](ctx)
} else {
mockedReponse[key] = mock.response[key]
}
})
if (mock) {
Object.assign(ctx.response, mockedReponse)
2015-11-19 17:48:31 +00:00
// options.verbose('mocked response', JSON.stringify(mockedReponse))
// options.verbose('actual response', JSON.stringify(ctx.response))
2015-11-19 16:03:01 +00:00
}
2015-11-18 16:37:16 +00:00
} else {
return next()
}
}
}
2015-11-13 15:33:19 +00:00
process.on('unhandledRejection', (reason, p) => {
throw reason
})
2015-11-19 10:01:04 +00:00
/**
* The `from` and `to` routes are specified using [express route-paths](http://expressjs.com/guide/routing.html#route-paths)
*
* @example
* ```json
* {
* "rewrite": [
* { "from": "/css/*", "to": "/build/styles/$1" },
* { "from": "/npm/*", "to": "http://registry.npmjs.org/$1" },
* { "from": "/:user/repos/:name", "to": "https://api.github.com/repos/:user/:name" }
* ]
* }
* ```
*
* @typedef rewriteRule
* @property from {string} - request route
* @property to {string} - target route
*/
2015-11-19 10:17:02 +00:00
/**
* @external KoaApplication
* @see https://github.com/koajs/koa/blob/master/docs/api/index.md#application
*/