-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.js
More file actions
91 lines (86 loc) · 3.01 KB
/
server.js
File metadata and controls
91 lines (86 loc) · 3.01 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
const config = require('./config');
const polka = require('polka');
const markets = require('./lib/markets');
const forexRates = require('./lib/openexchangerates');
const startupTimeout = config.get('startupTimeoutSeconds') * 1000;
let started = false;
const getHandler = (req, res) => {
const action = req.params.action;
let exchange = req.params.exchange;
exchange = exchange.split(',');
exchange.clean('');
const pair = req.params.pair;
const amount = Number(req.params.amount);
let message = `[api] GET ${action} ${exchange} ${pair}`;
if (amount) {
message += ` ${amount}`;
}
console.log(message);
res.setHeader('Content-Type', 'application/json');
const requestCurrencyCodes = pair.match(/.{1,3}/g);
const requestCurrency = requestCurrencyCodes[0].toUpperCase();
const targetCurrency = req.params.targetCurrency && req.params.targetCurrency.toUpperCase() || 'USD';
let validExchanges = true;
exchange.forEach((ex) => {
if (!config.get('exchanges')[ex]) {
validExchanges = false;
}
});
if (!validExchanges) {
res.statusCode = 400;
return res.end(JSON.stringify({
error: 'Invalid request'
}));
}
switch (action) {
case 'buy':
res.end(JSON.stringify(forexRates.convertFromUSD(markets.getMarketBuyPrice(exchange, pair, amount), requestCurrency), null, 4));
break;
case 'sell':
res.end(JSON.stringify(forexRates.convertFromUSD(markets.getMarketSellPrice(exchange, pair, amount), requestCurrency), null, 4));
break;
case 'orderbook':
res.end(JSON.stringify(markets.getOrderBook(exchange, pair), null, 4));
break;
case 'convert':
try {
res.end(JSON.stringify({rate: markets.getConversionRate(exchange, pair, forexRates.convertToUSD(amount, targetCurrency))}, null, 4));
} catch (e) {
console.error(e);
res.statusCode = 500;
res.end(JSON.stringify({error: e.message}));
}
break;
default:
res.statusCode = 400;
res.end(JSON.stringify({
error: 'Invalid request'
}));
}
};
async function start() {
setTimeout(() => {
if (!started) {
console.log('Process not started after timeout', config.get('startupTimeoutSeconds'), 'seconds. Killing process.');
process.exit(1);
}
}, startupTimeout);
await Promise.all([
forexRates.start(),
markets.start()
]);
await polka()
.get('/:action/:exchange/:pair', getHandler)
.get('/:action/:exchange/:pair/:amount', getHandler)
.get('/:action/:exchange/:pair/:amount/:targetCurrency', getHandler)
.listen(config.get('port'));
console.log(`Listening on port ${config.get('port')}`);
started = true;
}
(async () => {
try {
await start();
} catch (e) {
console.error(e);
}
})();