Example of Delete
- Let's create an endpoint to delete user from the database, create
deleteUser.js
into directorycontrollers->users
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
in directory transaction.users.jsrouters
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/
don't forget to change the HTTP METHOD transactions/updateusers/delete?userId=1POST,
to GETGET,PATCHPATCHDELETE 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.
-END-