Repository navigation
Expand file tree
/
Copy pathserver.js
More file actions
107 lines (86 loc) · 1.94 KB
/
Copy pathserver.js
File metadata and controls
107 lines (86 loc) · 1.94 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
97
98
99
100
101
102
103
104
105
106
107
/**
* Only for apis.is production environment
*/
if (process.env.NODE_ENV === 'production') {
process.chdir('/apis/current')
}
import express from 'express'
import expressMetrics from 'express-metrics'
import fileModule from 'file'
import { EventEmitter as EE } from 'events'
import statuses from 'statuses'
import config from './config'
import cache from './lib/cache'
import cors from './lib/cors'
import makeDebug from 'debug'
const debug = makeDebug('server')
const app = express()
app.use(expressMetrics({
port: 8091,
}))
module.exports = app
/**
* Set the spacing to 0 for shorter output
*/
app.set('json spaces', 0)
/**
* Create an event listener for app
*/
EE.call(app)
/**
* Cross-origin resource sharing
*/
app.use(cors())
/**
* Caching layer
*/
app.use(cache())
/**
* Set up endpoints
*/
fileModule.walkSync('./endpoints', (dirPath, dirs, endpoints) => {
function requireEndpoint(endpoint) {
if (endpoint.indexOf('.DS_Store') === -1) {
require(`./${dirPath}/${endpoint}`)
}
}
if (endpoints && dirPath.indexOf('test') < 0) {
endpoints.forEach(requireEndpoint)
}
})
app.use((error, req, res, next) => {
let code = 500
let message = 'Unknown error'
if (res.headersSent) {
console.error('Headers already sent')
return next()
}
if (typeof error === 'number') {
code = error
message = statuses[code] || message
} else if (
typeof error === 'object' &&
error.message &&
error.message.length === 3 &&
!isNaN(error.message)) {
code = error.message
message = statuses[code] || message
} else {
// Other errors that might have been swallowed
debug(error.stack)
message = error.message
}
code = parseInt(code, 10)
res.status(code).json({ error: message })
})
/**
* Start the server
*/
app.listen(config.port, () => {
app.emit('ready')
})
app.on('ready', () => {
if (!config.testing) {
debug('Server running at port:', config.port)
}
})