Skip to main content

Example of Update

  1. Let's create an endpoint to update user balance into the database, create updateBalance.js into directory controllers->transactions

Screenshot 2024-04-25 140346.png

2.  Write down using this code

const connection = require("../../services/database");

const updateBalance = async (req, res) => {
	const { userId, amount } = 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",
		});
	}
	// Update the balance
	try {
		await connection
			.promise()
			.query(`UPDATE users SET balance = ${amount} WHERE id = ${userId}`);
		// Return success if balance is upadated
		return res.json({
			success: true,
			data: null,
			error: null,
		});
	} catch {
		console.error("Error:", error);
		return res.status(500).json({
			success: false,
			data: null,
			error: error.message,
		});
	}
};
module.exports = updateBalance;

3. Go to transaction.js in directory routers and add the line below, this time we will use patch() since we want to update a single value.

const express = require("express");
const getBalance = require("../controllers/transactions/getBalance");
//add this line 👇
const updateBalance = require("../controllers/transactions/updateBalance");
const transactionsRouter = express.Router();

transactionsRouter.get("/balance", getBalance);
//add this line 👇
transactionsRouter.patch("/update", updateBalance);

module.exports = transactionsRouter;

4. Let's run your application again, and use postman with  localhost:5000/transactions/update don't forget to change the HTTP METHOD POST,GET to PATCH then send the userId and the amount that we want to change it to in body with JSON

//example of JSON that we will be sending in the body
{   
	"userId":"1"
    "amount":"50000"
}
  • You will see the result like this.

Screenshot 2024-04-25 143407.png

-END-