Use separate modules, get config from env

This commit is contained in:
Michael Jackson
2016-04-30 16:52:43 -07:00
parent d74f619b5e
commit a14c6cd90b
4 changed files with 67 additions and 54 deletions

19
modules/ServerUtils.js Normal file
View File

@ -0,0 +1,19 @@
import cors from 'cors'
import express from 'express'
import { createRequestHandler } from 'npm-http-server'
import { logStats } from './StatsUtils'
export const createServer = (options = {}) => {
const app = express()
app.disable('x-powered-by')
app.use(cors())
app.use(express.static('public', { maxAge: 60000 }))
if (options.redisURL)
app.use(logStats(options.redisURL))
app.use(createRequestHandler(options))
return app
}

27
modules/StatsUtils.js Normal file
View File

@ -0,0 +1,27 @@
import redis from 'redis'
import onFinished from 'on-finished'
const URLFormat = /^\/((?:@[^\/@]+\/)?[^\/@]+)(?:@([^\/]+))?(\/.*)?$/
export const logStats = (redisURL) => {
const redisClient = redis.createClient(redisURL)
return (req, res, next) => {
onFinished(res, () => {
const path = req.path
if (res.statusCode === 200 && path.charAt(path.length - 1) !== '/') {
redisClient.zincrby([ 'request-paths', 1, path ])
const match = URLFormat.exec(path)
if (match) {
const packageName = match[1]
redisClient.zincrby([ 'package-requests', 1, packageName ])
}
}
})
next()
}
}