-
Notifications
You must be signed in to change notification settings - Fork 39
Expand file tree
/
Copy pathSceHttpServer.js
More file actions
155 lines (143 loc) · 4.56 KB
/
Copy pathSceHttpServer.js
File metadata and controls
155 lines (143 loc) · 4.56 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
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
const express = require('express');
const bodyParser = require('body-parser');
const cookieParser = require('cookie-parser');
const cors = require('cors');
const http = require('http');
const mongoose = require('mongoose');
mongoose.Promise = require('bluebird');
const url = require('url');
const { PathParser } = require('./PathParser');
const logger = require('./logger');
const { MetricsHandler, register } = require('./metrics');
/**
* Class responsible for resolving paths of API endpoints and combining them
* them into an express server.
*/
class SceHttpServer {
/**
* Store port information, create express server object and configure
* BodyParser options.
* @param {(String|Array<String>)} pathToEndpoints The path to a single
* server file, directory or array of directories/files;
* @param {Number} port The port for the server to listen on.
* @param {String} prefix The prefix of the api endpoints to send requests
* to, e.g. /api/Event/addEvent, with /api/ being the prefix.
*/
constructor(pathToEndpoints, port, prefix = '/api/') {
const testEnv = process.env.NODE_ENV === 'test';
this.database = testEnv ? 'sce_core_test' : 'sce_core';
this.port = port;
this.pathToEndpoints = pathToEndpoints;
this.prefix = prefix;
this.app = express();
this.app.locals.title = 'Core v4';
this.app.locals.email = 'test@test.com';
this.app.use(cors());
this.app.use(cookieParser());
this.app.use(
bodyParser.json({
// support JSON-encoded request bodies
limit: '50mb',
strict: true,
})
);
this.app.use(
bodyParser.urlencoded({
// support URL-encoded request bodies
limit: '50mb',
extended: true,
})
);
}
async init() {
this.registerMetricsMiddleware();
await this.initializeEndpoints();
}
registerMetricsMiddleware() {
this.app.use((req, res, next) => {
res.on('finish', () => {
// req.originalUrl can look like /api/path?key=value
const parsedUrl = url.parse(req.originalUrl, true);
MetricsHandler.endpointHits.inc({
method: req.method,
// using the above example, pathname looks like '/api/path'
route: parsedUrl.pathname,
statusCode: res.statusCode,
});
});
next();
});
// metrics
this.app.get('/metrics', async (_, res) => {
res.setHeader('Content-Type', register.contentType);
res.end(await register.metrics());
});
}
/**
* This function is responsible for taking the pathToEndpoints instance
* variable and resolving API endpoints from it.
*/
async initializeEndpoints() {
const requireList = await PathParser.parsePath(this.pathToEndpoints);
requireList.map((route) => {
try {
this.app.use(this.prefix + route.endpointName, require(route.filePath));
MetricsHandler.errorLoadingExpressRoute.labels(route.endpointName).set(0);
} catch (e) {
MetricsHandler.errorLoadingExpressRoute.labels(route.endpointName).set(1);
logger.error(
`error importing ${route.filePath} to handle: ${route.endpointName}:`,
e
);
}
});
}
/**
* Create the http server, connect to MongoDB and start listening on
* the supplied port.
*/
openConnection() {
const { port } = this;
this.server = http.createServer(this.app);
this.connectToMongoDb();
this.server.listen(port, function() {
console.debug(`Now listening on port ${port}`);
});
}
/**
* Initialize a connection to MongoDB.
*/
connectToMongoDb() {
let dbHost = process.env.DATABASE_HOST || '127.0.0.1';
this.mongoose = mongoose;
this.mongoose
.connect(`mongodb://${dbHost}:27017/${this.database}`, {
promiseLibrary: require('bluebird'),
useNewUrlParser: true,
useUnifiedTopology: true,
useCreateIndex: true,
})
.then(() => { })
.catch((error) => {
throw error;
});
}
/**
* Return the current instance of the HTTP server. This function is useful
* for making chai HTTP requests in our API testing files.
* @returns {http.Server} The current instance of the HTTP server.
*/
getServerInstance() {
return this.server;
}
/**
* Close the connection to MongoDB and stop the server.
* @param {Function|null} done A function supplied by mocha as a callback to
* signify that we have completed stopping the server.
*/
closeConnection(done = null) {
this.server.close();
this.mongoose.connection.close(done);
}
}
module.exports = { SceHttpServer };