Skip to main content

Example of Delete

  1. Let's create an endpoint to delete user from the database, create deleteUser.js into directory controllers->users

Screenshot 2024-04-25 162736.png

2.  Write down using this code

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

const updateBalancedeleteUser = async (req, res) => {
	const { userId, amount }userId = req.body;query.userId;
	// 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)checkUserId) {
		return res.json({
			success: false,
			data: null,
			error: "Invalid input",
		});
	}
	// Update the balance
	try {
		await connection
			.promise()
			.query(`UPDATEDELETE FROM users SET balance = ${amount} WHERE id = ${userId}`);
		// Return success if balancethe data is upadateddeleted
		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 = updateBalance;deleteUser;

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

const express = require("express");
const getBalancegetAll = require("../controllers/transactions/getBalance"users/getAll");
const create = require("../controllers/users/create");
//add this line 👇
const updateBalancedeleteUser = require("../controllers/transactions/updateBalance"users/deleteUser");
const transactionsRouterusersRouter = express.Router();

transactionsRouter.usersRouter.get("/balance"all", getBalance)getAll);
usersRouter.post("/create", create);
//add this line 👇
transactionsRouter.patch(usersRouter.delete("/update"delete", updateBalance)deleteUser);

module.exports = transactionsRouter;usersRouter;

4. Let's run your application again, and use postman with  localhost:5000/transactions/updateusers/delete?userId=1 don't forget to change the HTTP METHOD POST,GETGET,PATCH to PATCHDELETE 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.pngScreenshot 2024-04-25 163833.png

-END-