feature/improved the getting of rates

This commit is contained in:
Joaquin committed 2025-05-06 21:26:45 -07:00
1 parent 93a5c45dd9
commit 17f11c85df
9 files changed
+44 -58

No files matched your search

+4 -14
View File
@@ -6,12 +6,11 @@ const path = require('path');
const joi = require('joi'); const joi = require('joi');
require('dotenv').config(); require('dotenv').config();
const app = express(); const app = express();
const port = process.env.PORT || 3000; const port = process.env.PORT || 3000;
const mongoURI = process.env.mongoURI || "mongodb://localhost:27017/"; const mongoURI = process.env.mongoURI;
const database = process.env.database || "knoldus"; // Database name const database = process.env.database; // Database name
const secret = process.env.secret || "123-secret-xyz"; const secret = process.env.secret || "123-secret-xyz";
/*** Sessions ***/ /*** Sessions ***/
@@ -34,13 +33,14 @@ app.use(express.json());
const { connectMongo, getCollection } = require("./src/database/connection"); const { connectMongo, getCollection } = require("./src/database/connection");
let users; let users;
let rates;
async function initDatabase() { async function initDatabase() {
const db = await connectMongo(mongoURI, database); const db = await connectMongo(mongoURI, database);
// For any collection, init here // For any collection, init here
users = await getCollection(db, "users"); users = await getCollection(db, "users");
plans = await getCollection(db, "plans"); plans = await getCollection(db, "plans");
currencies = await getCollection(db, "currencies"); rates = await getCollection(db, "rates");
} }
/*** ROUTINGS ***/ /*** ROUTINGS ***/
@@ -72,16 +72,6 @@ app.get('/aboutUs', (req, res) => {
return res.status(status.Ok); return res.status(status.Ok);
}); });
app.post('/api/location', async (req,res) => {
const { latitude, longitude } = req.body;
const response = await fetch(`https://maps.googleapis.com/maps/api/geocode/json?latlng=${latitude},${longitude}&result_type=country&key=${process.env.geolocation_api}`);
const data = await response.json();
res.json(data);
});
// Initialize database and start app // Initialize database and start app
initDatabase().then(() => { initDatabase().then(() => {
console.log("Successfully connected to MongoDB"); console.log("Successfully connected to MongoDB");
-6
View File
@@ -1,6 +0,0 @@
async function convert(from) {
const res = await fetch(`https://api.frankfurter.dev/v1/latest?base=${from}`);
const data = await res.json();
return data;
}
+7 -30
View File
@@ -1,43 +1,20 @@
async function diffCountries() {
const res = await fetch("/static/json/countries.json");
const data = await res.json();
return data.countries;
}
function getLocation() { function getLocation() {
if (navigator.geolocation) { if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(success, error); navigator.geolocation.getCurrentPosition(getLatestExchange, error);
} }
} }
async function success(position) { async function getLatestExchange(position) {
const { latitude, longitude } = position.coords; let lat = position.coords.latitude;
let countryCurrency; let lon = position.coords.longitude;
const res = await fetch(`/exRates/${lat}/${lon}`);
const countries = await diffCountries();
const res = await fetch("api/location" , {
method: "POST",
headers: {
"Content-Type": "application/json"
},
body: JSON.stringify({ latitude, longitude })
});
const data = await res.json(); const data = await res.json();
countries.forEach(country => { console.log(data);
if (country.country === data.results[0].formatted_address) {
countryCurrency = country.currency_abbreviation;
convert(countryCurrency);
}
});
} }
function error(err) { function error(err) {
console.error("Geolocation error: ", err); console.error("Geolocation error: ", err);
} }
//getLocation(); getLocation();
+13
View File
@@ -1,4 +1,5 @@
const status = require("../util/statuses"); const status = require("../util/statuses");
const getRates = require("../util/exchangeRate");
const bcrypt = require('bcrypt'); const bcrypt = require('bcrypt');
const joi = require("joi"); const joi = require("joi");
const salt = 12; const salt = 12;
@@ -222,5 +223,17 @@ module.exports = (middleware, users, plans) => {
}); });
}); });
router.get("/exRates/:lat/:lon", async (req, res) => {
if (!req.session.rates || Object.keys(req.session.rates).length == 0) {
const response = await fetch(`https://maps.googleapis.com/maps/api/geocode/json?latlng=${req.params.lat},${req.params.lon}&result_type=country&key=${process.env.geolocation_api}`);
const data = await response.json();
let country = data.results[0].formatted_address;
req.session.rates = await getRates(country);
}
return res.status(status.Ok).send({ rates: req.session.rates });
})
return router; return router;
}; };
File renamed without changes.
-6
View File
@@ -1,6 +0,0 @@
const { getCollection } = require('./src/database/connection');
async function saveExchangeRates() {
const { currencies } = getCollection();
await currencies.insertMany(convert());
}
+18
View File
@@ -0,0 +1,18 @@
const countries = require("./countries.json").countries;
async function getRates(country) {
let abbr;
countries.forEach(c => {
if (c.country === country) {
abbr = c.currency_abbreviation;
}
});
const res = await fetch(`https://api.frankfurter.dev/v1/latest?base=${abbr}`);
const data = await res.json();
let rates = data.rates;
return rates;
}
module.exports = getRates;
+2
View File
@@ -11,5 +11,7 @@
<% } %> <% } %>
</main> </main>
<script src="/static/scripts/geolocation.js"></script>
<%- include("./partials/navBar") %> <%- include("./partials/navBar") %>
<%- include("./partials/footer") %> <%- include("./partials/footer") %>
-2
View File
@@ -5,7 +5,5 @@
</div> </div>
</div> </div>
</footer> </footer>
<script src="/static/scripts/exchangeRate.js"></script>
<script src="/static/scripts/geolocation.js"></script>
</body> </body>
</html> </html>