Assignment : Integration with frontend
1. Download the frontend from this link https://drive.google.com/file/d/1UuALet56_czOseatkx2-jCsgUwWiYFAO/view?usp=sharingthen run npm i
when you run it should look like this
then npm i axios
2. Then go to your backend run npm i cors
then add the code below to your index.js
const express = require("express");
const app = express();
//add this line 👇
const cors = require("cors");
const usersRouter = require("./routers/users");
const transactionsRouter = require("./routers/transactions");
const port = 5000;
app.use(express.json());
//add this line 👇
app.use(cors({ origin: ["http://localhost:5173"], credentials: true }));
app.use("/users", usersRouter);
app.use("/transactions", transactionsRouter);
app.listen(port, () => {
console.log(`Example app listening on port ${port}`);
});
3. Then go to frontend->src->pages->Homepage.jsx
add this codethese
import axios from "axios";
//edit the getBalance 👇
const getBalance = async (userId) => {
const balance = await axios.get(
`http://localhost:5000/transactions/balance?userId=${userId}`
);
setUserData({ balance: balance.data.data.balance });
};
useEffect(() => {
getBalance(1);
}, []);
4. When restart the balance on your web should be base on your database
5. Go to your backend in the directory controllers->transactions
create deposit.js
6. write down this code
const connection = require("../../services/database");
const deposit = async (req, res) => {
const { userId, amount, note } = req.body;
// Check if userId and amount is number or not
const checkUserId = new RegExp(/^\d+$/).test(userId);
const checkAmount = new RegExp(/^\d+$/).test(amount);
// Return error if the userId and amount are null or it's not a number
if (!userId || !checkUserId || !amount || !checkAmount) {
return res.json({
success: false,
data: null,
error: "Invalid input",
});
}
try {
// Get user data
const userDataQuery = await connection
.promise()
.query(`SELECT firstname FROM users WHERE id = ${userId}`);
const firstname = userDataQuery[0][0].firstname;
if (!firstname) {
return res.status(404).json({
success: false,
data: null,
error: "User not found",
});
}
// Insert the transaction log to the database
await connection
.promise()
.query(
`INSERT INTO banks (owner, sender, amount, type, bank, note) VALUES ('${userId}', '${firstname}', '${amount}', 'deposit', 'SCB', '${note}')`
);
// Update the balance
await connection
.promise()
.query(
`UPDATE users SET balance = balance + ${amount} WHERE id = ${userId}`
);
// Return success if balance is upadated
return res.json({
success: true,
data: null,
error: null,
});
} catch (error) {
console.error("Error:", error);
return res.status(500).json({
success: false,
data: null,
error: error.message,
});
}
};
module.exports = deposit;
7. Add this to transaction.js
in directory routers
const express = require("express");
const getBalance = require("../controllers/transactions/getBalance");
const updateBalance = require("../controllers/transactions/updateBalance");
//add this line 👇
const deposit = require("../controllers/transactions/deposit");
const transactionsRouter = express.Router();
transactionsRouter.get("/balance", getBalance);
transactionsRouter.patch("/update", updateBalance);
//add this line 👇
transactionsRouter.post("/deposit", deposit);
module.exports = transactionsRouter;
8. Go to your Homepage.jsx
and update the handleDeposit
function
const handleDeposit = async (amount, note) => {
await axios.post(`http://localhost:5000/transactions/deposit`, {
userId: 1,
amount: amount,
note: note,
});
// call the function to update the balance after we make a deposit
getBalance(1);
};
9. Now it's your turn try to make the /withdraw
and /all
endpoint in transactions controllers work in the backend and then integrate with frontend
Hints
Withdraw
- When writing the endpoint don't forget to make sure that if the balance is more than the amount that you are going to withdraw
- The balance need to be deduct with the amount
getAllTransactions
- Hints uncomment this in directory
components->HomePage->TransactionCard.jsx
when doing the/transactions/all
- Assign the value to the useState of
transactions,setTransactions
-END-