DEV Community

Ahmet Akinsel
Ahmet Akinsel

Posted on β€’ Edited on

4 2

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

Tiugo image

Modular, Fast, and Built for Developers

CKEditor 5 gives you full control over your editing experience. A modular architecture means you get high performance, fewer re-renders and a setup that scales with your needs.

Start now

Top comments (0)

nextjs tutorial video

Youtube Tutorial Series πŸ“Ί

So you built a Next.js app, but you need a clear view of the entire operation flow to be able to identify performance bottlenecks before you launch. But how do you get started? Get the essentials on tracing for Next.js from @nikolovlazar in this video series πŸ‘€

Watch the Youtube series

πŸ‘‹ Kindness is contagious

Engage with a wealth of insights in this thoughtful article, valued within the supportive DEV Community. Coders of every background are welcome to join in and add to our collective wisdom.

A sincere "thank you" often brightens someone’s day. Share your gratitude in the comments below!

On DEV, the act of sharing knowledge eases our journey and fortifies our community ties. Found value in this? A quick thank you to the author can make a significant impact.

Okay