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

200 lines
6.0 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 url = require('url')
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-19 19:27:36 +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
2015-11-19 19:27:36 +00:00
* @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 = '*'
}
2015-11-19 19:27:36 +00:00
const debug = require('debug')('local-web-server')
2015-11-18 16:37:16 +00:00
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')
const bodyParser = require('koa-bodyparser')
2015-11-19 19:27:36 +00:00
const mw = require('./middleware')
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
2015-11-19 19:27:36 +00:00
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) {
2015-11-19 19:27:36 +00:00
debug('proxy rewrite', `${route.from} -> ${route.to}`)
app.use(_.all(route.from, mw.proxyRequest(route, app)))
2015-11-16 20:47:34 +00:00
} else {
const rewrite = require('koa-rewrite')
2015-11-19 19:27:36 +00:00
const rmw = rewrite(route.from, route.to)
rmw._name = 'rewrite'
app.use(rmw)
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) {
2015-11-19 19:27:36 +00:00
debug('forbid', options.forbid.join(', '))
app.use(mw.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) {
2015-11-19 19:27:36 +00:00
debug('mime override', JSON.stringify(options.mime))
app.use(mw.mime(options.mime))
2015-11-13 11:26:02 +00:00
}
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-19 19:27:36 +00:00
debug('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 */
2015-11-19 19:27:36 +00:00
app.use(mw.mockResponses({ root: options.static.root }))
2015-11-18 16:37:16 +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-19 19:27:36 +00:00
debug('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
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
*/