DEV Community

Ahmet Akinsel
Ahmet Akinsel

Posted on • Updated on

How to create a delete endpoint with node.js and MySql

Define your endpoint on routes.js file.

router.delete( "/delete-user/:userId", authentication, authorise({ roles: [ADMIN] }), deleteUserById );

In this endpoint we use url, middlewares and controller.

  • First define your url,
  • Check if the user logged in, (authentication)
  • Authorise if user is admin, guest what so ever. (authorise- OPTIONAL)

  • define the controller.

Our endpoint deletes user records by user id.That means it checks user's id from req.params, validates it with yup then removes user with action function then it gives the response.

const removeUserById = require("~root/actions/users/removeUserById");
const handleAPIError = require("~root/utils/handleAPIError");
const deleteUserByIdSchema = require("./schemas/deleteUserByIdSchema");

const deleteUserById = async (req, res) => {
  const { userId } = req.params;

  try {
    await deleteUserByIdSchema.validate(
      { userId },
      {
        abortEarly: false
      }
    );

    await removeUserById({
      userId
    });

    res.status(200).send();

  } catch (err) {
    handleAPIError(res, err);
  }
};

module.exports = deleteUserById;
Enter fullscreen mode Exit fullscreen mode

Quick tip: Controller:"delete" (Controllers always named as CRUD operations. Thats why controllers always named as delete,put,post,get etc.) => Action:"remove"

  • After creating your controller create your action. Action is an async function. It has userId as parameter and it returns {deleteUser}.
const deleteUserById = require("./queries/deleteUserById");

const removeUserById = async ({ userId }) => {
  const deletedUser = await deleteUserById({ userId });
  return { deletedUser };
};

module.exports = removeUserById;
Enter fullscreen mode Exit fullscreen mode
  • Once you create your action you need a query for it. Create a queries folder inside your removeUserById folder. We are using MySQL for this project. Basically we need to tell our database that "find the user record associated with user_id from users table".
const { submitQuery } = require("~root/lib/database");

const deleteUserById = ({ userId }) => submitQuery`
  DELETE FROM users   
  WHERE user_id = ${userId};
`;

module.exports = deleteUserById;
Enter fullscreen mode Exit fullscreen mode
  • After creating your query we can validate the process with yup. Create a schemas folder inside deleteUserById folder. You can validate if user_id is number,required?, positive(!-), integer? or has a label("").
const yup = require("yup");

const deleteCuttingToolByIdSchema = yup.object().shape({
  userId: yup
  .number()
  .required()
  .positive()
  .integer()
  .label("User ID")
  .typeError("User ID must be a number.")
});

 module.exports = deleteCuttingToolByIdSchema
Enter fullscreen mode Exit fullscreen mode
  • After this process your need to play with projects database-schema. In this scenario we have a parent table which is users table. Also there are 2 child tables. That's why we can use ON DELETE CASCADE command from MySql. This command deletes the record for every records that includes ON CASCADE DELETE command. It follows. That's why we put that command to FOREING KEYs. Below changes should be made to any table which references user_id column.

FOREIGN KEY (user_id) REFERENCES users(user_id) ON DELETE CASCADE

  • Test it on Postman by making a call to DELETE /delete-user/1

Top comments (0)