-
Notifications
You must be signed in to change notification settings - Fork 0
/
app.js
50 lines (39 loc) · 1.33 KB
/
app.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
require("dotenv").config();
const express = require("express");
const axios = require("axios");
const app = express();
const PORT = process.env.PORT || 3000;
let exchangeRates = {};
const API_URL = `https://v6.exchangerate-api.com/v6/${process.env.API_KEY}/latest/USD`;
async function fetchExchangeRates() {
try {
const response = await axios.get(API_URL);
exchangeRates = response.data.conversion_rates;
console.log("Exchange rates updated.");
} catch (error) {
console.error("Error fetching exchange rates:", error);
}
}
fetchExchangeRates();
setInterval(fetchExchangeRates, 24 * 60 * 60 * 1000);
app.get("/get", (req, res) => {
const { from, to } = req.query;
if (!from || !to) {
return res
.status(400)
.json({ error: 'Please provide both "from" and "to" query parameters.' });
}
const fromRate = exchangeRates[from];
const toRate = exchangeRates[to];
if (!fromRate || !toRate) {
return res.status(400).json({ error: "Invalid currency code provided." });
}
const conversionRate = toRate / fromRate;
res.json({ from, to, rate: conversionRate });
});
app.get("/currencies", (req, res) => {
res.json({ currencies: Object.keys(exchangeRates) });
});
app.listen(PORT, () => {
console.log(`Server is running on http://localhost:${PORT}`);
});