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

186 lines
4.7 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-08 22:09:07 +00:00
const Koa = require('koa')
const convert = require('koa-convert')
2015-11-13 11:42:16 +00:00
const cors = require('kcors')
2015-11-15 11:59:45 +00:00
const _ = require('koa-route')
const pathToRegexp = require('path-to-regexp')
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
*
* @param [options] {object} - options
* @param [options.forbid] {regexp[]} - a list of forbidden routes.
2015-11-15 21:15:25 +00:00
* @alias module:local-web-server
* @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: {},
log: {},
2015-11-13 19:55:52 +00:00
compress: false,
forbid: [],
2015-11-16 13:22:51 +00:00
rewrite: []
2015-11-08 22:09:07 +00:00
}, options)
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-16 20:47:34 +00:00
/* CORS: allow from any origin */
app.use(cors())
2015-11-15 11:59:45 +00:00
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) {
app.use(_.all(route.from, proxyRequest(route)))
} else {
const rewrite = require('koa-rewrite')
app.use(rewrite(route.from, route.to))
}
}
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) {
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) {
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')
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-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')
2015-11-15 14:53:25 +00:00
app.use(_.all('*', function * () {
yield send(this, options.spa, { root: process.cwd() })
}))
}
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
2015-11-16 20:47:34 +00:00
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(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-13 15:33:19 +00:00
process.on('unhandledRejection', (reason, p) => {
throw reason
})