-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathindex.ts
99 lines (82 loc) · 2.39 KB
/
index.ts
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
import * as http from 'http'
import * as express from 'express'
import * as bodyParser from 'body-parser'
import * as morgan from 'morgan'
import {env, PipelineStages} from './src/environment'
import {persistError} from './src/logger'
import {dataRouter} from './src/routes/data'
import {tokenRouter as authRouter} from './src/routes/auth'
import {misc} from './src/routes/misc'
import {ClientFacingError} from './src/utils'
import {adminOnlyHandler} from './src/requestUtils'
const helmet = require('helmet')
const app = express()
app.use(helmet())
app.use(morgan('tiny'))
const server = http.createServer(app)
const port = 3001
server.listen(port)
app.use(bodyParser.json({limit: '20mb'}))
if (env.trustProxy() === true) {
app.enable('trust proxy')
}
// CORS: https://enable-cors.org/
app.use((req, res, next) => {
res.setHeader('Access-Control-Allow-Origin', '*')
res.setHeader('Access-Control-Allow-Headers', '*')
res.setHeader(
'Access-Control-Allow-Methods',
'GET, POST, PUT, DELETE, HEAD, OPTIONS'
)
if (req.method === 'OPTIONS') {
return res.status(200).end()
}
return next()
})
authRouter(app)
dataRouter(app)
misc(app)
if (env.pipelineStage() === PipelineStages.development) {
app.post(
'/debug/set-env/:key/:value',
adminOnlyHandler(
async (req, res) => {
return {
key: req.params.key as string,
value: req.params.value as string,
}
},
async ({key, value}) => {
process.env[key] = value
return {
status: 200,
body: {},
}
}
)
)
}
app.get('*', (req, res, next) => res.status(404).end())
app.post('*', (req, res, next) => res.status(404).end())
app.use(
(
err: Error,
req: express.Request,
res: express.Response,
next: express.NextFunction
) => {
const message =
err instanceof ClientFacingError ? err.message : 'Something went wrong'
const status = err instanceof ClientFacingError ? err.status : 500
res.status(status).json({error: message})
persistError(err.message, err.stack!)
}
)
console.log(`Starting server in ${env.pipelineStage()} mode`)
console.log(`Local: http://localhost:${port}/`)
process.on('unhandledRejection', error => {
if (error) {
const [message, stack = 'Stack is missing'] = error instanceof Error ? [error.message, error.stack] : [JSON.stringify(error)]
persistError(message, stack)
}
})