unpkg/server/index.js

105 lines
2.7 KiB
JavaScript
Raw Normal View History

/*eslint-disable no-console*/
const http = require('http')
const express = require('express')
const cors = require('cors')
const morgan = require('morgan')
2017-05-25 18:25:42 +00:00
const middleware = require('./middleware')
const { fetchStats } = require('./cloudflare')
const fs = require('fs')
const path = require('path')
const sendHomePage = (publicDir) => {
const html = fs.readFileSync(path.join(publicDir, 'index.html'), 'utf8')
return (req, res, next) => {
fetchStats((error, stats) => {
if (error) {
next(error)
} else {
res.set('Cache-Control', 'public, max-age=60')
res.send(
2017-05-19 17:59:04 +00:00
// Replace the __SERVER_DATA__ token that was added to the
// HTML file in the build process (see scripts/build.js).
html.replace('__SERVER_DATA__', JSON.stringify({
cloudflareStats: stats
}))
)
}
})
}
}
const errorHandler = (err, req, res, next) => {
res.status(500).send('<p>Internal Server Error</p>')
console.error(err.stack)
next(err)
}
morgan.token('fwd', (req) => req.get('x-forwarded-for').replace(/\s/g, ''))
const createServer = (config) => {
const app = express()
app.disable('x-powered-by')
2017-06-06 22:50:46 +00:00
app.use(morgan(process.env.NODE_ENV === 'production'
// Modified version of the Heroku router's log format
// https://devcenter.heroku.com/articles/http-routing#heroku-router-log-format
? 'method=:method path=":url" host=:req[host] request_id=:req[x-request-id] cf_ray=:req[cf-ray] fwd=:fwd status=:status bytes=:res[content-length]'
2017-06-06 22:50:46 +00:00
: 'dev'
))
2017-05-25 04:38:06 +00:00
app.use(errorHandler)
app.use(cors())
app.get('/', sendHomePage(config.publicDir))
app.use(express.static(config.publicDir, {
2017-06-06 22:50:46 +00:00
maxAge: '365d'
}))
2017-08-12 17:38:50 +00:00
app.use(middleware())
const server = http.createServer(app)
// Heroku dynos automatically timeout after 30s. Set our
// own timeout here to force sockets to close before that.
// https://devcenter.heroku.com/articles/request-timeout
2017-06-06 22:50:46 +00:00
server.setTimeout(25000, (socket) => {
const message = `Timeout of 25 seconds exceeded`
socket.end([
`HTTP/1.1 503 Service Unavailable`,
`Date: ${(new Date).toGMTString()}`,
`Content-Type: text/plain`,
`Content-Length: ${Buffer.byteLength(message)}`,
`Connection: close`,
``,
message
].join(`\r\n`))
})
return server
}
const defaultServerConfig = {
id: 1,
port: parseInt(process.env.PORT, 10) || 5000,
2017-08-12 17:38:50 +00:00
publicDir: 'public'
}
const startServer = (serverConfig = {}) => {
const config = Object.assign({}, defaultServerConfig, serverConfig)
const server = createServer(config)
server.listen(config.port, () => {
console.log('Server #%s listening on port %s, Ctrl+C to stop', config.id, config.port)
})
}
module.exports = {
createServer,
startServer
}