-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathindex.js
executable file
·126 lines (109 loc) · 4.42 KB
/
index.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
115
116
117
118
119
120
121
122
123
124
125
126
#!/usr/bin/env node
/**
* This file index.js, is part of the Learning Pass project.
*
* Copyright 2021 Andrew Nisbet, Edmonton Public Library
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
'use strict';
// Dependencies
const http = require('http');
const https = require('https');
const StringDecoder = require('string_decoder').StringDecoder;
const config = require('./config');
// Read cert and key
const fs = require('fs');
const handlers = require('./lib/handlers');
const logger = require('./logger');
// The http server should respond to all requests with a string.
const httpServer = http.createServer(function(req, res){
unifiedServer(req, res);
});
// Start the server and listen on port 3000
httpServer.listen(config.getHttpPort(), function() {
logger.info('The server is listening on HTTP port '+config.getHttpPort()+', env: ' + config.getEnvName());
});
// The https server.
const httpsServerOptions = {
// since we want the file to be read before proceeding...
// 'key' : fs.readFileSync('./https/key.pem'),
// 'cert' : fs.readFileSync('./https/cert.pem')
'key' : fs.readFileSync(config.getSSLKey()),
'cert' : fs.readFileSync(config.getSSLCertificate())
};
const httpsServer = https.createServer(httpsServerOptions, function(req, res){
unifiedServer(req, res);
});
// Start the server and listen on port 3000
httpsServer.listen(config.getHttpsPort(), function() {
logger.info('The server is listening on HTTPS port '+config.getHttpsPort()+', env: ' + config.getEnvName());
});
// Handle creating both http and https servers.
const unifiedServer = function(req, res) {
// Get url and parse it.
const baseURL = 'http://' + req.headers.host + '/';
// use this instead of parse() which is now deprecated.
const parsedUrl = new URL(req.url, baseURL);
// Get the path from the URL.
let path = parsedUrl.pathname;
let trimmedPath = path.replace(/^\/+|\/+$/g, '');
// get the query string as an object.
// Use search with new URL()
let queryStringObject = parsedUrl.searchParams;
// Make sure you are consistent using either upperCase or lowerCase 'GET' or 'get'.
// This is part of the HEADER not part of the request itself.
let method = req.method.toLowerCase();
// get the headers.
let headers = req.headers;
// get the payload (if any)
let decoder = new StringDecoder('utf-8');
let buffer = '';
// on the event called 'data' we want this callback
// to handle the event that was emitted.
req.on('data', function(data){
buffer += decoder.write(data);
});
req.on('end', function(){
buffer += decoder.end();
// choose the handler to route to.
let chooseHandler = typeof(router[trimmedPath]) !== 'undefined' ? router[trimmedPath] : handlers.notFound;
// if one is not found use notFound handler.
let data = {
'trimmedPath' : trimmedPath,
'queryStringObject' : queryStringObject,
'method' : method,
'headers' : headers,
'payload' : buffer
};
chooseHandler(data, function(statusCode, payload){
// use the status defined by the handler or default to 200
statusCode = typeof(statusCode) == 'number' ? statusCode : 200;
// use the payload defined by the handler, or default to an empty object
payload = typeof(payload) == 'object' ? payload : {};
// convert the payload from an object to a string.
let payloadString = JSON.stringify(payload);
// return the response
// Let the user know we are returning JSON
res.setHeader('Content-type', 'application/json');
res.writeHead(statusCode);
res.end(payloadString);
});
});
};
// definition of a request router.
const router = {
'register' : handlers.register,
'status' : handlers.status,
'version' : handlers.version
};