forked from yeschef-challenges/currency-converter
-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.js
67 lines (61 loc) · 1.83 KB
/
main.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
const http = require('http');
const rates = {
usd: 1
};
function setRates(urlParts, dataObj) {
//todo: store/update a rate
}
function convert(requestParams) {
//todo: convert between two currencies
}
http.createServer((req, res) => {
const urlParts = req.url.split("/");
if (req.method === "GET") {
switch (urlParts[1]) {
case "convert":
try {
res.end(convert(urlParts));
} catch (e) {
res.statusCode = 401;
res.end(e.message);
}
break;
default:
res.statusCode = 401;
res.end("bad request");
}
} else if (req.method === "POST") {
let data = []
req.on('data', chunk => {
data.push(chunk)
});
req.on('end', () => {
console.log("request data is " + data);
const reqDataObj = {};
data.join().split("&").forEach(param => {
const paramParts = param.split("=");
reqDataObj[paramParts[0]] = paramParts[1];
});
switch (urlParts[1]) {
case "rates":
try {
setRates(urlParts, reqDataObj);
res.statusCode = 200;
res.end("Ok");
} catch (e) {
res.statusCode = 401;
res.end(e.message);
}
break;
default:
res.statusCode = 401;
res.end("bad request");
}
});
} else {
res.statusCode = 401;
res.end("bad request");
}
console.log(req.url);
}).listen(8080);
console.log("server is up and running on port 8080")