Skip to content

Commit

Permalink
Implemented appending record to database
Browse files Browse the repository at this point in the history
only base functionality
solves #66
  • Loading branch information
skorphil committed Mar 8, 2024
1 parent 4d63d22 commit 5a95710
Show file tree
Hide file tree
Showing 5 changed files with 97 additions and 71 deletions.
32 changes: 32 additions & 0 deletions models/record.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
import mongoose from "mongoose";
const Schema = mongoose.Schema;

const RecordSchema = new Schema(
{
date: Number,
quotes: [
{
baseCurrency: String,
rates: [{ currency: String, rate: Number }],
},
],
institutions: [
{
name: String,
country: String,
assets: [
{
currency: String,
amount: Number,
isEarning: Boolean,
description: String,
},
],
},
],
},
{ timestamps: true }
);

module.exports =
mongoose.models.Record || mongoose.model("Record", RecordSchema);
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@
"private": true,
"scripts": {
"all": "npm-run-all -p storybook dev",
"dev": "next dev",
"dev": "NODE_OPTIONS='--inspect' next dev",
"build": "next build",
"start": "next start",
"lint": "next lint",
Expand Down
84 changes: 14 additions & 70 deletions serverActions/appendRecord.js
Original file line number Diff line number Diff line change
@@ -1,8 +1,9 @@
"use server";

import mongoose from "mongoose";
import Ajv from "ajv";
const dbUri = process.env.MONGO_URI;
import connect from "utils/mongooseConnect";
import Record from "models/record";
import { getQuotes } from "./getQuotes";

const baseCurrencies = ["usd", "rub", "amd", "brl"];
const ajv = new Ajv();
Expand All @@ -21,7 +22,6 @@ const recordSchema = {
country: {
type: "string",
maxLength: 2,
minLength: 2,
},
assets: {
type: "array",
Expand All @@ -31,7 +31,6 @@ const recordSchema = {
properties: {
currency: {
type: "string",
maxLength: 3,
minLength: 3,
},
amount: {
Expand Down Expand Up @@ -59,10 +58,13 @@ const recordSchema = {

export async function appendRecord(formData) {
const isFormDataValid = ajv.validate(recordSchema, formData);
console.log("isFormDataValid", isFormDataValid);
if (!isFormDataValid) {
throw new Error(`Provided data has wrong structure: ${ajv.errorsText()}`);
}
// TODO add error handling to ui
// TODO add success handling to UI
// TODO prevent adding multiple records per month. Ask to override

const recordInstitutions = formData.institutions
.filter((institution) => !institution.isDeleted)
Expand All @@ -76,75 +78,17 @@ export async function appendRecord(formData) {
)
);

const record = {
const record = new Record({
date: Date.now(),
quotes: await getQuotes({ baseCurrencies, recordCurrencies }),
institutions: recordInstitutions,
};
});

console.log("record:", record);

// push to db
// if no database?

// await mongoose.connect(uri, {
// useNewUrlParser: true,
// serverSelectionTimeoutMS: 5000,
// socketTimeoutMS: 45000,
// family: 4, // Use IPv4, skip trying IPv6
// });
// console.log("models:", mongoose.models);

// console.log("Mongoose connected to MongoDB Atlas!");
// const kittySchema = new mongoose.Schema({
// name: String,
// });
// const Cat = mongoose.models.Cat || mongoose.model("Cat", kittySchema);
// console.log("Cat modeled");

// const fluffy = new Cat({ name: "fluffy" });
// fluffy.save;
}

async function getQuotes({ baseCurrencies, recordCurrencies }) {
const fetchUrls = recordCurrencies.map(
(currency) =>
`https://cdn.jsdelivr.net/npm/@fawazahmed0/currency-api@latest/v1/currencies/${currency}.json`
);

async function fetchQuotes(fetchUrls) {
try {
const promises = fetchUrls.map((url) => fetch(url));
const responses = await Promise.all(promises);
const data = await Promise.all(
responses.map((response) => response.json())
);
return data;
} catch (error) {
console.error(error);
}
try {
await connect();
await record.save();
console.log("Document saved to db");
} catch (error) {
throw new Error("Error saving document:", error);
}

// TODO reformat quotes because currencies can be 4 or more symbols. and `usdtcny` will be unable to parse
/* [
{recordCurrency: target currencies}
{usd:[rub:90, amd:400...]}
{rub:[rub:1, usd: 0.01...]}
] */
const quotes = (await fetchQuotes(fetchUrls))
.map((quote) => {
const { date, ...rest } = quote;
const [baseCurrency] = Object.keys(rest);
const quotes = Object.entries(rest[baseCurrency]);
debugger;
const targetQuotes = quotes
.filter(([key]) => baseCurrencies.includes(key) && key != baseCurrency)
.map(([currency, value]) => ({
[`${baseCurrency}${currency}`]: value,
}));
return targetQuotes;
})
.flat();

return quotes;
}
38 changes: 38 additions & 0 deletions serverActions/getQuotes.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
"use server";

export async function getQuotes({ baseCurrencies, recordCurrencies }) {
const fetchUrls = recordCurrencies.map(
(currency) =>
`https://cdn.jsdelivr.net/npm/@fawazahmed0/currency-api@latest/v1/currencies/${currency}.json`
);

async function fetchQuotes(fetchUrls) {
try {
const promises = fetchUrls.map((url) => fetch(url));
const responses = await Promise.all(promises);
const data = await Promise.all(
responses.map((response) => response.json())
);
return data;
} catch (error) {
console.error(error);
}
}

const quotes = (await fetchQuotes(fetchUrls))
.map((quote) => {
const { date, ...rest } = quote;
const [baseCurrency] = Object.keys(rest);
const quotes = Object.entries(rest[baseCurrency]);
const targetQuotes = quotes
.filter(([key]) => baseCurrencies.includes(key))
.map(([currency, value]) => ({
currency: currency,
rate: value,
}));
return { baseCurrency: baseCurrency, rates: [...targetQuotes] };
})
.flat();

return quotes;
}
12 changes: 12 additions & 0 deletions utils/mongooseConnect.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
import mongoose from "mongoose";

const connect = async () => {
try {
await mongoose.connect(process.env.MONGO_URI);
console.log("Database connected!");
} catch (error) {
throw new Error("Connection failed!");
}
};

export default connect;

0 comments on commit 5a95710

Please sign in to comment.