Skip to main content

Assignment : Integration with frontend

    1.

    Let'sDownload createthe anfrontend endpointfrom this link https://drive.google.com/file/d/1bDBR5fE6xzYdnDro3AgVuHrwq4Tot7rQ/view?usp=sharing then run npm i when you run it should look like this

    Screenshot 2024-04-26 113905.png

    then npm i axios

    2.  Then go to deleteyour userbackend 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 code

    import axios from "axios";
    
    //edit the database,getBalance create👇
    deleteUser.jsconst getBalance = async (userId) => {
    		const balance = await axios.get(
    			`http://localhost:5000/transactions/balance?userId=${userId}`
    		);
    		setUserData({ balance: balance.data.data.balance });
    	};
    useEffect(() => {
    		getBalance(1);
    	}, []);
    into

    4. When restart the balance on your web should be base on your database

    5. Go to your backend in the directory controllers->userstransactions

    create deposit.js

    Screenshot 2024-04-25 162736.pngScreenshot 2024-04-26 121003.png

    2.6.  Writewrite down using this code

    const connection = require("../../services/database");
    
    const deleteUserdeposit = async (req, res) => {
    	const userId{ userId, amount, note } = req.query.userId;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)checkUserId || !amount || !checkAmount) {
    		return res.json({
    			success: false,
    			data: null,
    			error: "Invalid input",
    		});
    	}
    	try {
    		// Get user data
    		const userDataQuery = await connection
    			.promise()
    			.query(`DELETESELECT 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 th 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 the databalance is deletedupadated
    		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 = deleteUser;deposit;

    3.7. GoAdd this to users.transaction.js in directory routers and add the line below, this time we will use delete().

    const express = require("express");
    const getAllgetBalance = require("../controllers/users/getAll"transactions/getBalance");
    const createupdateBalance = require("../controllers/users/create"transactions/updateBalance");
    //add this line 👇
    const deleteUserdeposit = require("../controllers/users/deleteUser"transactions/deposit");
    const usersRoutertransactionsRouter = express.Router();
    
    usersRouter.transactionsRouter.get("/all"balance", getAll)getBalance);
    usersRouter.post(transactionsRouter.patch("/create"update", create)updateBalance);
    //add this line 👇
    usersRouter.delete(transactionsRouter.post("/delete"deposit", deleteUser)deposit);
    module.exports = usersRouter;transactionsRouter;

    4.8. Let'sGo runto your application again,Homepage.jsx and useupdate postmanthe 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 localhost:5000/users/delete?userId=1frontend

    Hints

     Withdraw

      When writing the endpoint don't forget to changemake sure that if the HTTPbalance METHODis POST,GET,PATCHmore to DELETE
        You will seethan the resultamount likethat this.you are going to withdraw The balance need to be deduct with the amount

        Screenshot 2024-04-25 164011.pnggetAllTransactions

            Hints uncomment this in directory components->HomePage->TransactionCard.jsx when doing the /transactions/all Assign the value to the useState of transaction,setTransaction
            {/* {transactionList.map((transaction) => (
                                        <TransactionList
                                            key={transaction.bank_id}
                                            amount={transaction.amount}
                                            date={transaction.date}
                                            type={transaction.type}
                                        />
                                    ))} */}

            -END-