Last active
August 10, 2023 21:27
-
-
Save ferostabio/53c5914a85437a5d4296b30019a9f053 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import express from "express"; | |
import axios from "axios"; | |
import { createClient } from "redis"; | |
import { promisify } from "util"; | |
const app = express(); | |
const PORT = process.env.PORT || 3000; | |
const REDIS_URL = process.env.REDIS_URL; // Replace with actual one | |
export const URLS = { | |
DEFILLAMA_LEND_BORROW: "https://yields.llama.fi/lendBorrow", | |
DEFILLAMA_POOLS: "https://yields.llama.fi/pools", | |
}; | |
const FIFTEEN_MINUTES = 15 * 60 * 1000; | |
const THREE_DAYS = 3 * 24 * 60 * 60; | |
const client = createClient({ | |
url: REDIS_URL, | |
}); | |
async function fetchDataAndSaveToRedis() { | |
// Not sure if this is the right approach | |
const defillamaproxy = process.env.DEFILLAMA_PROXY; | |
const uri = { | |
lendBorrow: defillamaproxy | |
? defillamaproxy + "lendBorrow" | |
: URLS.DEFILLAMA_LEND_BORROW, | |
pools: defillamaproxy ? defillamaproxy + "pools" : URLS.DEFILLAMA_POOLS, | |
}; | |
try { | |
const [lendBorrows, pools] = await Promise.all([ | |
axios.get(uri.lendBorrow).then(({ data }) => data), | |
axios.get(uri.pools).then(({ data }) => data.data), | |
]); | |
client.set("lendBorrows", JSON.stringify(lendBorrows), { EX: THREE_DAYS }); | |
client.set("pools", JSON.stringify(pools), { EX: THREE_DAYS }); | |
console.log("Data fetched and saved to Redis."); | |
} catch (error) { | |
console.error("Error fetching data:", error); // This is the reason why we're doing this in the first place | |
} | |
} | |
app.get("/llama_financials", async (req, res) => { | |
try { | |
const [lendBorrows, pools] = await client | |
.multi() | |
.get("lendBorrows") | |
.get("pools") | |
.exec(); | |
const responseData = { | |
lendBorrows: lendBorrows ? JSON.parse(lendBorrows) : null, | |
pools: pools ? JSON.parse(pools) : null, | |
}; | |
res.json(responseData); | |
} catch (err) { | |
res.status(500).json({ error: "Error retrieving data" }); | |
} | |
}); | |
app.listen(PORT, async () => { | |
console.log(`Server is running on http://localhost:${PORT}`); | |
await client.connect(); | |
console.log("Connected to Redis"); | |
setInterval(fetchDataAndSaveToRedis, FIFTEEN_MINUTES); // fetch data every 15 minutes | |
fetchDataAndSaveToRedis(); // fetch data immediately when the server starts | |
}); | |
client.on("error", (err) => { | |
console.error("Redis error:", err); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment