database
{"account":[100,-100]}
script
const fs = require("fs/promises");
const express = require("express");
const cookieParser = require("cookie-parser");
const PORT = 3000;
const app = express();
app.use(express.json());
app.use(cookieParser());
app.get("/", async (req, res) => {
const accountValue = await getAccountValue();
res.json({ accountValue: accountValue });
});
app.get("/deposit", async (req, res) => {
await addTransaction(100);
const accountValue = await getAccountValue();
res.json({ accountValue: accountValue });
});
app.get("/withdrawal", async (req, res) => {
await addTransaction(-100);
const accountValue = await getAccountValue();
res.json({ accountValue: accountValue });
});
app.listen(PORT, () => {
console.log(`Server running on http://localhost:${PORT}`);
});
async function getDatabase() {
const values = await fs.readFile("./database.json");
const databse = JSON.parse(values);
return databse;
}
async function saveDatabase(database) {
return await fs.writeFile("./database.json", database, "utf-8");
}
async function getAccountValue() {
const databse = await getDatabase();
return databse.account.reduce((total, current) => {
return total + current;
}, 0);
}
async function addTransaction(value) {
const database = await getDatabase();
database.account.push(value);
return await saveDatabase(JSON.stringify(database));
}