-
Notifications
You must be signed in to change notification settings - Fork 1
/
app.js
92 lines (83 loc) · 2.68 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
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
const reqlib = require('app-root-path').require;
const config = require('config');
const express = require('express');
const fs = require('fs');
const git = require('simple-git/promise');
const https = require('https');
const moment = require('moment');
const db = reqlib('/db/db');
const { badRequest, notFound, errorHandler } = reqlib('/errors/errors');
const { authentication } = reqlib('/middlewares/authentication');
const { logger } = reqlib('/middlewares/logger');
// Create Express application
const serverConfig = config.get('server');
const app = express();
const appRouter = express.Router();
const adminApp = express();
const adminAppRouter = express.Router();
// Middlewares
if (logger) app.use(logger);
app.use(serverConfig.basePath, appRouter);
appRouter.use(authentication);
adminApp.use(serverConfig.basePath, adminAppRouter);
adminAppRouter.use(authentication);
adminAppRouter.use('/healthcheck', require('express-healthcheck')());
// GET /
adminAppRouter.get('/', async (req, res) => {
try {
const commit = await git().revparse(['--short', 'HEAD']);
const now = moment();
const info = {
meta: {
name: 'staff-fee-privilege-api',
time: now.format('YYYY-MM-DD HH:mm:ssZZ'),
unixTime: now.unix(),
commit: commit.trim(),
documentation: 'swagger.yaml',
},
};
res.send(info);
} catch (err) {
errorHandler(res, err);
}
});
// GET /staff-fee-privilege
appRouter.get('/staff-fee-privilege', async (req, res) => {
try {
const { query } = req;
if (!query.term && !query.osuId) {
res.status(400).send(badRequest('Term code or OSU ID need to be provided.'));
} else {
const result = await db.getStaffFeePrivilegesByQuery(query);
res.send(result);
}
} catch (err) {
errorHandler(res, err);
}
});
// GET /staff-fee-privilege/:id
appRouter.get('/staff-fee-privilege/:id', async (req, res) => {
try {
const { id } = req.params;
const [osuId, term] = id.split('-');
const result = await db.getStaffFeePrivilegesById({ osuId, term });
if (!result) {
res.status(404).send(notFound('A staff fee privilege record with the specified ID was not found.'));
} else {
res.send(result);
}
} catch (err) {
errorHandler(res, err);
}
});
// Create and start HTTPS servers
const httpsOptions = {
key: fs.readFileSync(serverConfig.keyPath),
cert: fs.readFileSync(serverConfig.certPath),
secureProtocol: serverConfig.secureProtocol,
};
const httpsServer = https.createServer(httpsOptions, app);
const adminHttpsServer = https.createServer(httpsOptions, adminApp);
httpsServer.listen(serverConfig.port);
adminHttpsServer.listen(serverConfig.adminPort);
module.exports = { app };