-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathapp.js
68 lines (54 loc) · 1.97 KB
/
app.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
'use strict'
require('dotenv').config()
const express = require('express')
const bodyParser = require('body-parser')
const helmet = require('helmet')
const logger = require('./config/logger')
const keys = require('./config/keys')
const courses = require('./routes/courses')
const terms = require('./routes/terms')
const options = require('./routes/options')
const request = require('./routes/request')
const auth = require('./services/authentication')
const api = require('./controllers/api')
/** The express server used to serve the API */
const app = express()
/** Middleware for getting information from a POST request */
app.use(bodyParser.json())
/** Middleware to set headers to protect Express */
app.use(helmet())
/** HTTP Logging */
app.use(logger.morgan)
/** Middleware to authenticate our users */
app.use(auth.authenticate)
/** Routes for our API */
app.use('/courses', courses)
app.use('/terms', terms)
app.use('/options', options)
app.use('/request', request)
/** Default route handler */
app.get('*', (req, res, next) => {
let ip = req.headers['x-forwarded-for'] || req.connection.remoteAddress
logger.log('warn', `[${ip}] Tried to access an invalid endpoint`)
res.status(404).json({msg: 'The resource requested does not exist'})
})
/** Error handler */
app.use((err, req, res, next) => {
logger.log('error', (req.errorText === undefined ? 'An error has occured' : req.errorText))
logger.log('error', err)
res.status(500).json({msg: `An error has occured. Please try again later`, text: req.errorText})
})
/** Start the API */
if (process.env.NODE_ENV !== 'testing') {
app.listen(keys.express.port, () => {
logger.log('info', `Server started on port ${keys.express.port}`)
api.updateCache()
.then(() => logger.log('info', 'Initial cache update complete'))
.catch((error) => {
logger.log('error', 'An error has occured during the initial cache update')
logger.log('error', error)
})
})
}
/** For testing */
module.exports = app