generated from dm-academy/node-svc
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.js
More file actions
171 lines (138 loc) · 4.99 KB
/
server.js
File metadata and controls
171 lines (138 loc) · 4.99 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
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
// Node-Svc. Simple microservice. Includes both Express and Fetch. Calls itself,
// or can be replicated and will round-robin requests among peers.
'use strict';
const arrNodes = [ "35.194.5.71" ] // you might need this for K8S
// vary these constants according to how many VMs you have deployed
//const arrNodes = [ "localhost" ] // for testing on GCS
//const arrNodes = [ "node-svc-01" ]
//const arrNodes = [ "node-svc-01", "node-svc-02" ]
//const arrNodes = [ "node-svc-01", "node-svc-02" , "node-svc-03" ]
const express = require('express');
const fetch = require('node-fetch');
const bodyParser = require('body-parser')
// Constants
const PORT = 30100;
const HOST = '0.0.0.0';
const app = express();
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
app.get('/999', (req, res) => {
(async () => {
console.warn("***SHUTDOWN SIGNAL***");
res.write("Shutting down.");
res.status(200).end();
return process.exit(999);
})();
})
app.get('/0?', (req, res) => { // matches either / or /0
(async () => {
// A simple change is to alter the returned data,
// e.g. change "ThisAction" to "Action"
res.write(dateIPStamp({ "ThisAction":"GET" }, req.ip));
res.status(200).end();
console.log('Console: / Server returned success on get.');
})();
});
// app.get('/:depth(\d+)', (req, res) => { // WHY does this not work
app.get('/:depth', (req, res) => { // everything else but / or /0
console.log("/n GET, making GET subrequest");
if (!boolValidateRoute(res, req.params.depth)) return;
let strURL = buildURL(req.params.depth);
(async () => {
const response = await fetch(strURL);
const json = await response.json();
console.log(json);
res.write(dateIPStamp(json, req.ip));
res.status(200).end();
console.log('Console: /1 Server returned success on get.');
})();
});
app.post('/0?', (req, res) => { // matches either / or /0
console.log ("Console: entered / post");
console.log("Console: / received " + JSON.stringify(req.body));
let recd = req.body;
recd.action = "POST";
let stampedRecd = dateIPStamp(recd, req.ip);
res.write(stampedRecd); //
res.status(200).end();
console.log('Console: / returned ' + stampedRecd);
});
app.post('/:depth', (req, res) => {
console.log ("Console: /n POST");
if (!boolValidateRoute(res, req.params.depth)) return;
let strURL = buildURL(req.params.depth);
(async () => {
console.log("/n POST trying subrequest");
const recd = await req.body;
const headers = {"Content-Type": "application/json"};
const postData = await JSON.stringify({recd});
const response = await fetch(strURL, { method: 'POST', headers: headers, body: postData});
const json = await response.json();
console.log(json);
res.write(dateIPStamp(json, req.ip));
res.status(200).end();
console.log('Console: /1 Server returned success on get.');
})();
});
///////////////////////////////////////////////////
///////////// Main body////////////////////////////
///////////////////////////////////////////////////
app.listen(PORT, HOST);
console.log(`Running on ${PORT}`);
// test a simple self-get
console.log('Console: request is testing a simple self-get')
fetch('http://localhost:' + PORT)
.then(response => response.json())
.then(data => console.log(data));
// test a simple self-post
console.log('Console: request is testing a simple self-post')
const url ='http://localhost:' + PORT;
const headers = {
"Content-Type": "application/json"
};
const postData = JSON.stringify({
"firstName": "myFirstName",
"lastName": "myLastName"
});
fetch(url, { method: 'POST', headers: headers, body: postData})
.then((res) => {
return res.json()
})
.then((json) => {
console.log(json);
});
function boolValidateRoute (res, strRoute) {
if (!isNumeric(strRoute)) {
console.log("non-numeric path attempted");
res.write("error, only numeric depth path supported");
res.status(405).end();
return false; } else { return true; }
}
function dateIPStamp(recdJSON, someIP) {
console.log ("DateIPStamp reached with " + JSON.stringify(recdJSON) + " " + someIP);
let now = new Date();
if (!recdJSON.hasOwnProperty("arrTimeStamp")) {
recdJSON.arrTimeStamp = [ someIP + " " + now ];
} else {
recdJSON["arrTimeStamp"].push(someIP + " " + now)
};
let strReturnJSON = JSON.stringify(recdJSON);
return(strReturnJSON);
}
function isNumeric(strIn) {
// returns bool
let re = /\d+/;
return (re.test(strIn));
}
function buildURL (strLevel) {
// what is the formula for which node to call?
// given x levels and n nodes
// x % n where x>n, else n
let intCurrLevel = parseInt(strLevel);
let nextLevel = intCurrLevel - 1;
let numNodes = arrNodes.length; // to be derived from arrNodes
let nextNode = nextLevel >= numNodes ? nextLevel % numNodes : nextLevel;
let strURL = "http://"+ arrNodes[nextNode] + ":" + PORT + "/" + nextLevel;
console.log ("returning URL " + strURL);
return(strURL);
}