-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.js
More file actions
69 lines (56 loc) · 1.78 KB
/
index.js
File metadata and controls
69 lines (56 loc) · 1.78 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
/**
* Title: NODE EXPRESS CACHING FETCHED DATA with REDIS
* Description: This code is a demo on caching data with Redis to lower latency and speed up load time
* Credits: API credits to www.messari.io
*/
const express = require("express");
const redis = require("redis");
const fetch = require("node-fetch");
let PORT = process.env.PORT || 4000;
let REDIS_PORT = process.env.PORT || 6379;
const client = redis.createClient(REDIS_PORT);
const app = express();
// FETCH DATA FROM API
// credits to www.messari.io
async function coin(request, response) {
try {
console.log("fetching data...");
const { coin } = request.params;
const respond = await fetch(
`https://data.messari.io/api/v1/assets/${coin}/profile`
);
const data = await respond.json();
// current variable convert json to string format
const current = JSON.stringify(data);
// set cache with expiration
client.setex("coin", 3600, current);
return response.send({ Coin: coin, 'Fresh Data': data });
} catch (error) {
response.send({ 'Something went wrong on "GET_COIN" function': error });
}
}
//CACHE MIDDLEWARE
function cache(request, response, next) {
const { coin } = request.params;
// retreive data from the cache
client.get("coin", (error, data) => {
//parsed data to convert string to json format
const parsed = JSON.parse(data);
if (error)
response.send({
"Something went wrong on getting data from the cache": error,
});
if (data !== null && parsed.data.slug === coin) {
return response.send({ Coin: coin, 'Cached Data': parsed });
}
else {
next();
}
});
}
//ROUTER
app.get("/crypto/:coin", cache, coin);
//PORT LISTENER
app.listen(PORT, () => {
console.log("listening to port", PORT);
});