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

83 lines
2.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-08 22:09:07 +00:00
const Koa = require('koa')
const serve = require('koa-static')
const convert = require('koa-convert')
const serveIndex = require('koa-serve-index')
2015-11-10 21:50:56 +00:00
const morgan = require('koa-morgan')
2015-11-12 23:02:38 +00:00
const compress = require('koa-compress')
const streamLogStats = require('stream-log-stats')
2015-11-08 22:09:07 +00:00
/**
* @module local-web-server
*/
module.exports = getApp
process.on('unhandledRejection', (reason, p) => {
throw reason
})
function getApp (options) {
2015-11-10 21:50:56 +00:00
options = Object.assign({
static: {},
serveIndex: {},
log: {},
2015-11-12 23:02:38 +00:00
compress: false
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-13 11:26:02 +00:00
// CORS
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-12 23:02:38 +00:00
if (options.compress) {
app.use(convert(compress()))
}
/* special case log formats */
if (log.format) {
2015-11-12 23:02:38 +00:00
if (log.format === 'none'){
log.format = undefined
} else if (log.format === 'logstalgia') {
morgan.token('date', logstalgiaDate)
2015-11-12 23:02:38 +00:00
log.format = 'combined'
}
/* if no specific log format was requested, show log stats */
2015-11-12 23:02:38 +00:00
} else {
log.format = 'common'
log.options.stream = streamLogStats({ refreshRate: 500 })
2015-11-10 21:50:56 +00:00
}
if (log.format) app.use(convert(morgan.middleware(log.format, log.options)))
2015-11-12 23:02:38 +00:00
2015-11-10 21:50:56 +00:00
if (options.static.root) {
app.use(convert(serve(options.static.root, options.static.options)))
}
if (options.serveIndex.path) {
app.use(convert(serveIndex(options.serveIndex.path, options.serveIndex.options)))
}
2015-11-12 23:02:38 +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)', '')
}