unpkg/server/createServer.js

68 lines
1.7 KiB
JavaScript
Raw Normal View History

2018-02-17 00:00:06 +00:00
const http = require("http");
const express = require("express");
const morgan = require("morgan");
2017-11-25 21:25:01 +00:00
2018-02-17 00:00:06 +00:00
const staticAssets = require("./middleware/staticAssets");
const createRouter = require("./createRouter");
2017-11-25 21:25:01 +00:00
2018-01-03 21:19:29 +00:00
morgan.token("fwd", req => {
2018-02-17 00:00:06 +00:00
return req.get("x-forwarded-for").replace(/\s/g, "");
});
2017-08-13 00:23:40 +00:00
function errorHandler(err, req, res, next) {
2018-02-17 00:00:06 +00:00
console.error(err.stack);
2017-11-10 07:04:43 +00:00
2017-10-20 12:01:10 +00:00
res
.status(500)
2017-11-25 21:25:01 +00:00
.type("text")
2018-02-17 00:00:06 +00:00
.send("Internal Server Error");
2017-11-10 07:04:43 +00:00
2018-02-17 00:00:06 +00:00
next(err);
}
2018-02-17 00:00:06 +00:00
function createServer(publicDir, statsFile) {
const app = express();
2018-02-17 00:00:06 +00:00
app.disable("x-powered-by");
2017-11-25 21:25:01 +00:00
if (process.env.NODE_ENV !== "test") {
2017-10-20 12:01:10 +00:00
app.use(
morgan(
2018-02-17 00:00:06 +00:00
// 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-10-20 12:01:10 +00:00
)
2018-02-17 00:00:06 +00:00
);
2017-08-19 00:32:57 +00:00
}
2017-05-25 04:38:06 +00:00
2018-02-17 00:00:06 +00:00
app.use(errorHandler);
app.use(express.static(publicDir, { maxAge: "365d" }));
app.use(staticAssets(statsFile));
app.use(createRouter());
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
server.setTimeout(25000, socket => {
const message = `Timeout of 25 seconds exceeded`;
socket.end(
[
"HTTP/1.1 503 Service Unavailable",
"Date: " + new Date().toGMTString(),
"Content-Length: " + Buffer.byteLength(message),
"Content-Type: text/plain",
"Connection: close",
"",
message
].join("\r\n")
);
});
return server;
}
2018-02-17 00:00:06 +00:00
module.exports = createServer;