-
Notifications
You must be signed in to change notification settings - Fork 0
/
server.js
76 lines (61 loc) · 2.37 KB
/
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
require('colors');
const jsonServer = require('json-server');
const server = jsonServer.create();
const router = jsonServer.router('db.json');
const middlewares = jsonServer.defaults();
server.use(middlewares);
server.get('/convert', (req, res) => {
const { from, to, amount } = req.query;
if (!from) console.error('❌ No "from" value provided');
if (!to) console.error('❌ No "to" value provided');
if (!amount) console.error('❌ No "amount" value provided');
const sanitisedFrom = from && from.toUpperCase();
const sanitisedTo = to && to.toUpperCase();
const sanitisedAmount = amount && parseInt(amount);
const rates = router.db.getState().rates;
const fromRate = rates.find((rate) => rate.base === sanitisedFrom);
if (!fromRate) console.error(`⚠️ Could not find currency: ${sanitisedFrom}`);
const toRate = fromRate && fromRate.rates[sanitisedTo];
res.jsonp({
from: sanitisedFrom,
to: sanitisedTo,
amount: sanitisedAmount,
convertedAmount: toRate * sanitisedAmount,
});
});
server.get('/rates/:currencyCode', (req, res) => {
const { currencyCode } = req.params;
const sanitisedCurrencyCode = currencyCode && currencyCode.toUpperCase();
const rates = router.db.getState().rates;
const currencyWithRates = rates.find((rate) => rate.base === sanitisedCurrencyCode);
if (!currencyWithRates) console.error(`⚠️ Could not find currency: ${sanitisedCurrencyCode}`);
const copiedRates = { ...currencyWithRates.rates };
Object.entries(currencyWithRates.rates).map(([key, value]) => {
if (key !== currencyCode) {
copiedRates[key] = parseFloat((Math.random() * (value + 1 - value) + value).toPrecision(8));
}
return copiedRates[key];
});
res.jsonp({ ...currencyWithRates, rates: copiedRates });
});
server.use(router);
const app = server.listen(3002, () => {
console.log(
`
----- Welcome to the -----
_____ _ ______ ____
/ ____| | | ____/ __ \\
| | | | | |__ | | | |
| | | | | __|| | | |
| |____| |____| |___| |__| |
\\_____|______|______\\____/
----- Frontend Test -----
`.brightBlue,
' Resources'.bold,
`\n http://localhost:${app.address().port}/convert`,
`\n http://localhost:${app.address().port}/currencies`,
`\n http://localhost:${app.address().port}/rates\n`,
'\n Home'.bold,
`\n http://localhost:${app.address().port}\n`,
);
});