aboutsummaryrefslogtreecommitdiffstats
path: root/lib/rates.js
blob: 80c22bf0137ed45b5d33afc2b2d28659aa186e4a (plain) (blame)
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
const axios = require("axios");
const fs = require("fs");

let binance = require("./binance")();

let fetchRates;
(fetchRates = async () => {
  let date, fx;

  try {
    ({ date, fx } = JSON.parse(fs.readFileSync("fx")));
  } catch {
    l.warn("Failed to read fx file");
  }

  let today = JSON.stringify(new Date())
    .replace(/T.*/, "")
    .replace(/"/, "");

  if (date !== today) {
    try {
      let {
        data: { rates: fx }
      } = await axios.get("https://api.exchangerate.host/latest?base=USD");
      fs.writeFileSync("fx", JSON.stringify({ date, fx }));
    } catch (e) {
      try {
        let {
          data: { rates: fx }
        } = await axios.get(
          `http://data.fixer.io/api/latest?access_key=${config.fixer}`
        );
        let USD = fx["USD"];
        Object.keys(fx).map(k => {
          fx[k] = parseFloat((fx[k] / fx["USD"]).toFixed(6));
        });
        fs.writeFileSync("fx", JSON.stringify({ date, fx }));
      } catch (e) {
        l.error("error fetching rates", e.message);
      }
    }
  }

  app.set("fx", fx);

  setTimeout(fetchRates, 7200000);
})();

app.get(
  "/rates",
  ah(async (req, res, next) => {
    res.send(app.get("rates"));
  })
);

setInterval(() => {
  broadcast("rate", app.get("last"));
}, 1000);

setInterval(() => {
  binance.terminate();
  binance = require("./binance")();
}, 360000);