-
Notifications
You must be signed in to change notification settings - Fork 130
/
index.js
116 lines (98 loc) · 2.71 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
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
require('dotenv').config();
const db = require('db');
const poloniex = require('lib/poloniex');
const ExchangeRate = require('db/models/ExchangeRate');
const socket = require('./socket');
const { parseJSON, polyfill } = require('lib/common');
const log = require('lib/log');
const currencyMap = require('lib/poloniex/currencyPairMap');
const redis = require('redis');
const publisher = redis.createClient();
const initialize = async () => {
await db.connect();
await registerInitialExchangeRate();
socket.connect();
};
async function registerInitialExchangeRate() {
const tickers = await poloniex.getTickers();
// removes all the data from the collection (only for temporary use)
await ExchangeRate.drop();
log('dropped exchangerate collection');
const keys = Object.keys(tickers);
const promises = keys.map(
key => {
const ticker = tickers[key];
if (!currencyMap[ticker.id.toString()]) {
return Promise.resolve();
}
const data = Object.assign({name: key}, ticker);
const exchangeRate = new ExchangeRate(data);
return exchangeRate.save();
}
);
try {
await Promise.all(promises);
} catch (e) {
console.log(e);
}
console.log('succeed!');
}
async function updateEntireRate() {
log('updating entire rate...');
const tickers = await poloniex.getTickers();
const keys = Object.keys(tickers);
const promises = keys.map(
key => {
return ExchangeRate.updateTicker(key, tickers[key]);
}
);
try {
await Promise.all(promises);
} catch (e) {
log.error('Oops, failed to update entire rate!');
return;
}
log('done');
}
const messageHandler = {
1002: async (data) => {
if (!data) return;
const converted = poloniex.convertToTickerObject(data);
const { name, ...rest } = converted;
if(!name) return;
if(name === 'NULL_NULL') return;
try {
await ExchangeRate.updateTicker(name, rest);
const { last, percentChange, baseVolume, quoteVolume } = converted;
const payload = {
name,
last: parseFloat(last),
percentChange: parseFloat(percentChange),
baseVolume: parseFloat(baseVolume),
quoteVolume: parseFloat(quoteVolume),
lastUpdated: new Date()
};
publisher.publish('general', JSON.stringify({
type: 'TICKER',
payload
}));
// log('Updated', name);
} catch (e) {
console.error(e);
}
}
};
socket.handleMessage = (message) => {
const parsed = parseJSON(message);
if (!parsed) {
return null;
}
const [type, meta, data] = parsed;
if (messageHandler[type]) {
messageHandler[type](data);
}
};
socket.handleRefresh = () => {
updateEntireRate();
};
initialize();