-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.js
More file actions
65 lines (53 loc) · 1.58 KB
/
server.js
File metadata and controls
65 lines (53 loc) · 1.58 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
const express = require("express");
const path = require("path");
const nFetch = require("node-fetch");
const app = express();
const port = 3000;
app.use(express.static(__dirname + "/client"));
app.get("/", (req, res) => {
res.render('index.html')
});
app.get("/api/current", async(req, res) => {
const end = parseInt((new Date().getTime() / 1000).toFixed(0));
const start = end - 86400;
const api = `https://api.cryptowat.ch/markets/kraken/btcusd/ohlc?after=${start}&before=${end}&periods=3600`;
const apiRes = await nFetch(api);
const jsonData = await apiRes.json();
const result = jsonData.result['3600'];
res.send(result);
});
const INTERVALS = [
60,
180,
300,
900,
1800,
3600,
7200,
14400,
21600,
43200,
86400,
259200,
604800
];
const optimalInterval = (start, end) => {
const goal = (end - start) / 50;
return INTERVALS.reduce((prev, curr) => {
return Math.abs(curr - goal) < Math.abs(prev - goal) ? curr : prev;
});
};
app.get("/api/history", async(req, res) => {
const start = req.query.start;
const end = req.query.end;
const interval =
optimalInterval(parseInt(start), parseInt(end)) || 3600;
const history = `https://api.cryptowat.ch/markets/kraken/btcusd/ohlc?after=${start}&before=${end}&periods=${interval}`;
const apiRes = await nFetch(history);
const jsonData = await apiRes.json();
const result = jsonData.result[interval];
res.send(result);
})
app.listen(port, () => {
console.log(`Example app listening at http://localhost:${port}`);
});