This repository has been archived by the owner on Mar 6, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
85 lines (66 loc) · 2.48 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
var http = require('http');
var https = require('https');
var url = require('url');
var StringDecoder = require('string_decoder').StringDecoder;
var config = require('./lib/config');
var fs = require('fs');
var handlers = require('./lib/handlers');
var _data = require('./lib/data');
var helpers = require('./lib/helpers');
var httpServer = http.createServer(function(req, res){
unifiedServer(req, res);
});
httpServer.listen(config.httpPort, function(){
console.log('HTTP server is listening on port ' + config.httpPort + ' in ' +config.envName+ ' mode');
});
var httpsServerOptions = {
'key': fs.readFileSync('./https/key.pem'),
'cert': fs.readFileSync('./https/cert.pem')
};
var httpsServer = https.createServer(httpsServerOptions,function(req, res){
unifiedServer(req, res);
});
httpsServer.listen(config.httpsPort, function(){
console.log('HTTPS server is listening on port ' + config.httpsPort + ' in ' +config.envName+ ' mode');
});
var unifiedServer = function(req, res){
var parsedUrl = url.parse(req.url, true);
var path = parsedUrl.pathname;
var trimmedPath = path.replace(/^\/+|\/+$/g, '');
var queryStringObject = parsedUrl.query;
var method = req.method.toLowerCase();
var headers = req.headers;
var decoder = new StringDecoder('utf-8');
var buffer = '';
req.on('data', function(data){
buffer += decoder.write(data);
});
req.on('end', function(){
buffer += decoder.end();
var chosenHandler = typeof(router[trimmedPath]) !== 'undefined' ? router[trimmedPath] : handlers.notFound;
var data = {
'trimmedPath': trimmedPath,
'queryStringObject': queryStringObject,
'method': method,
'headers': headers,
'payload': helpers.parseJsonToObject(buffer)
};
chosenHandler(data, function(statusCode, payload){
statusCode = typeof(statusCode) == 'number' ? statusCode : 200;
payload = typeof(payload) == 'object' ? payload : {};
var payloadString = JSON.stringify(payload);
res.setHeader('Content-Type', 'application/json');
res.writeHead(statusCode);
res.end(payloadString);
console.log('response:', statusCode, payloadString);
});
});
};
var router = {
"ping": handlers.ping,
"sample": handlers.sample,
"hello": handlers.hello,
"users": handlers.users,
"tokens": handlers.tokens,
"checks": handlers.checks
};