-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.js
More file actions
96 lines (83 loc) · 2.14 KB
/
server.js
File metadata and controls
96 lines (83 loc) · 2.14 KB
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
88
89
90
91
92
93
94
95
96
//
// Connects to database and runs server.
//
var fs = require('fs')
var pg = require('pg')
var cors = require('cors')
var morgan = require('morgan')
var express = require('express')
var bodyParser = require('body-parser')
var FileStreamRotator = require('file-stream-rotator')
//
// Configuration variables.
//
var port = process.env.PORT || 2000
var DB = require('./config/db')
var Config = require('./config/dev')
//
// Express application.
//
var app = express()
//
// Connect to the database and
// then start application. This
// handles errors as well.
//
console.log('Attempting database connection to: ' + DB.url)
pg.connect(DB.url, function (err, client, done) {
var _handle = function (err) {
//
// no error occurred, continue with the request
//
if (!err) {
return false
}
//
// An error occurred, remove the client from the connection pool.
// A truthy value passed to done will remove the connection from the pool
// instead of simply returning it to be reused.
// In this case, if we have successfully received a client (truthy)
// then it will be removed from the pool.
//
if (client) {
done(client)
}
console.log('Could not connect to PostgreSQL.')
console.log(err)
return true
}
//
// If the handler managed
// to handle the error correctly,
// continue. Otherwise, return false.
//
if (_handle(err)) {
return false
}
//
// Setup logger.
//
var logDirectory = __dirname + '/log'
fs.existsSync(logDirectory) || fs.mkdirSync(logDirectory)
var accessLogStream = FileStreamRotator.getStream({
filename: logDirectory + '/historic-api-%DATE%.log',
frequency: 'daily',
verbose: false
})
app.use(morgan('combined', {stream: accessLogStream}))
//
// Configure CORS and body parser.
//
app.use(cors())
app.use(bodyParser.json({ type: 'application/*+json' }))
app.use(bodyParser.urlencoded({ extended: false }))
//
// Load routes.
//
require('./app/routes.js')(app, client, done, Config)
//
// Start server.
//
console.log('Historic API (' + Config.version + ') running on port ' + port)
app.listen(port)
})