-
Notifications
You must be signed in to change notification settings - Fork 0
/
server.coffee
87 lines (67 loc) · 2.18 KB
/
server.coffee
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
# Usage: coffee server.coffee
express = require 'express'
winston = require 'winston'
papertrail = require('winston-papertrail').Papertrail
morgan = require 'morgan'
bodyParser = require 'body-parser'
compression = require 'compression'
timeout = require 'connect-timeout'
helmet = require 'helmet'
history = require 'connect-history-api-fallback'
prerender = require 'prerender-node'
enforceSSL = require './app/lib/enforce-ssl'
config = require './app/config'
devconfig = require './app/devconfig'
port = process.env.PORT or 3333
maxCacheAge = devconfig.time.cache * 60 * 1000 # page cache (in ms)
svTimeout = devconfig.time.timeout * 1000 # server timeout (in ms)
transports = [
new winston.transports.Console colorize: true
]
app = express()
staticFileMiddleware = express.static "#{__dirname}/public",
maxAge: maxCacheAge
if devconfig.enable.logger.remote
host = 'logs.papertrailapp.com'
options =
handleExceptions: true
host: host
port: 55976
colorize: true
transports.push(new papertrail options)
if devconfig.enable.logger.local
options =
filename: 'server.log'
maxsize: 2097152
transports.push(new winston.transports.File options)
logger = winston.createLogger transports: transports
logError = (err, src, error=true) ->
logFun = if error then logger.error else logger.warn
message = if src then "#{src} #{err.message}" else err.message
logFun message
sendError = (err, res, src, code=500) ->
res.status(code).send {error: err.message}
haltOnTimedout = (req, res, next) -> if !req.timedout then next()
winstonStream = write: (message, encoding) -> logger.info message
if devconfig.prod
app.use enforceSSL()
app.use helmet()
app.use staticFileMiddleware
app.use history()
app.use prerender
app.use timeout svTimeout
app.use morgan 'combined', {stream: winstonStream}
app.use haltOnTimedout
app.use bodyParser.text()
app.use haltOnTimedout
app.use compression()
app.use haltOnTimedout
app.use staticFileMiddleware
app.use haltOnTimedout
app.use (err, req, res, next) ->
logError err, 'app'
sendError err, res, 'app', 504
server = app.listen port, -> logger.info "Listening on port #{port}"
process.on 'SIGINT', ->
server.close()
process.exit()