-
Notifications
You must be signed in to change notification settings - Fork 1
/
original-server.js
114 lines (93 loc) · 2.51 KB
/
original-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
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
const debug = require('debug')('original-server')
const config = require('./configuration')
const https = require('https')
const fs = require('fs')
const express = require('express')
const cors = require('cors')
const path = require('path')
const app = express()
app.use(cors())
////////////////
/// FUNCTIONS
////////////////
const buildLogMessagePrefix = function(req, res) {
return res.statusCode + ' ' + req.method + ' ' + req.originalUrl
}
const logResponseToRequest = function(req, res) {
debug(buildLogMessagePrefix(req, res))
}
const getRandomShapeResponse = function() {
const shapes = [
'Circle',
'Triangle',
'Square',
'Rectangle'
]
return {
shape: shapes[Math.floor((Math.random() * shapes.length))]
}
}
const getRandomFormResponse = function() {
const forms = [
'Sphere',
'Cone',
'Cube',
'Box'
]
return {"form": forms[Math.floor((Math.random() * forms.length))]}
}
const buildHelloWorldResponse = function(res) {
res.json({
text: "Hello, World!",
})
}
const buildShapesResponse = function(res, protectionStatus) {
const response = getRandomShapeResponse()
res.json(response)
}
const buildFormsResponse = function(res, protectionStatus) {
const response = getRandomFormResponse()
res.json(response)
}
////////////////
// ENDPOINTS
////////////////
/**
* V1 ENDPOINTS
*/
// simple 'hello world' endpoint.
app.get('/v1/hello', function (req, res, next) {
logResponseToRequest(req, res)
buildHelloWorldResponse(res)
})
// shapes endpoint returns a random shape.
app.get('/v1/shapes', function(req, res, next) {
logResponseToRequest(req, res)
buildShapesResponse(res, 'unprotected')
})
// shapes endpoint returns a random form.
app.get('/v1/forms', function(req, res, next) {
logResponseToRequest(req, res)
buildFormsResponse(res, 'unprotected')
})
////////////
// SERVER
////////////
if (config.server.httpsEnabled) {
// Load the certificate and key data for our server to be hosted over HTTPS
const serverOptions = {
key: fs.readFileSync(config.server.certificateKey),
cert: fs.readFileSync(config.server.certificatePem),
requestCert: false,
rejectUnauthorized: false
}
// Create and run the HTTPS server
https.createServer(serverOptions, app).listen(config.server.httpPort, function() {
debug("Shapes server listening on %s", config.server.fullUrl)
})
} else {
// Create and run the HTTP server
app.listen(config.server.httpPort, function () {
debug("Shapes server listening on %s", config.server.fullUrl)
})
}