This repository was archived by the owner on Sep 9, 2020. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathserver.js
72 lines (60 loc) · 1.74 KB
/
server.js
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
// External modules
const debug = require('debug')
const nconf = require('nconf')
const Koa = require('koa')
const router = require('koa-router')({
prefix: '/api'
})
// Logging
const log = debug('robototes-website-api:server')
const logHTTP = debug('http')
// Load configuration
nconf.env()
.required([
'PORT',
'IP',
'DOMAIN',
'TBA_SECRET_KEY',
'DATABASE_HOST',
'DATABASE_PORT'
])
log('Loaded configuration')
// Load middleware
let middlewares = require('koa-load-middlewares')()
// Create a new app
const app = new Koa()
// Configure middleware
app.use(async (ctx, next) => {
logHTTP(`<-- ${ctx.path}`)
try {
await next()
// Get the status of any responses or assume the request wasn't handled
ctx.status = ctx.status || 404
// Throw any error codes, or just report and continue
if (ctx.status >= 400) ctx.throw(ctx.status)
else logHTTP(`\t--> ${ctx.status} OK`)
} catch (err) {
// Make sure our response reflects our error
ctx.status = err.status || 500 // Make sure we have a status code
// Tell Koa that we've handled an error
ctx.app.emit('err', err, ctx)
// Log the error and our response
logHTTP(err)
logHTTP(`\t--> ${err.status} NOT OK: ${err.message}`)
}
})
.use(middlewares.bodyparser())
.use(middlewares.compress()) // Compresses responses
log('Configured middleware')
// Link all endpoints to the router
require('./routes/thebluealliance')(router)
require('./routes/email')(router)
require('./routes/ping')(router)
// Add the routes
app.use(router.routes())
.use(router.allowedMethods())
log('Configured routing')
// Start the server
module.exports = app.listen(nconf.get('PORT'), nconf.get('IP'), () => {
log(`Server listening on port ${nconf.get('PORT')}`)
})