DEV Community

Cover image for Cloudinary and Postgresql - Deleting and Updating Images Using Nodejs
NJOKU SAMSON EBERE
NJOKU SAMSON EBERE

Posted on • Updated on

Cloudinary and Postgresql - Deleting and Updating Images Using Nodejs

Welcome πŸ€— to the concluding part of this tutorial. It's being a long roll. We are now able to see nodejs, cloudinary and postgresql as 3 persons working together to solve our problem.

Getting Started
Creating APIs
Delete API
Update API

We started with the introductory part on Setting Up a Simple, Secure and Robust Node JS Server up to Persisting and Retrieving images using cloudinary and Postgresql Through Nodejs.

Today we want to look at deleting and updating images on cloudinary.

Getting Started

As a prerequisite to this tutorial, please take the last tutorial to be up to speed.

If you are coming from the previous tutorial, then move to Creating APIs.

However, if you are just joining us, please find the starter project for this tutorial here.

At this point, I want to believe that we are all up to speed!!!

Now to the business of the article...

Creating APIs

Delete API

  • In the app.js file, start with the following code

// delete image
app.delete("delete-image/:cloudinary_id", (request, response) => {

});

Enter fullscreen mode Exit fullscreen mode
  • Next, we want to get the unique ID of the image we want to delete from the URL i.e cloudinary_id. So inside the code above add:

const { cloudinary_id } = request.params;

Enter fullscreen mode Exit fullscreen mode

We now start the deleting process

  • First, we delete from the cloudinary. Add the following code to delete the image from cloudinary

cloudinary.uploader
    .destroy(cloudinary_id)
    .then((result) => {
      response.status(200).send({
        message: "success",
        result,
      });
    })
    .catch((error) => {
      response.status(500).send({
        message: "Failure",
        error,
      });
    });

Enter fullscreen mode Exit fullscreen mode

At this point, our API can delete the image from cloudinary only (You can check it out in postman). However, we want to also get rid of the record we have in our postgres database

  • Second, we delete from our postgres database. To do so, replace the code in the then block with the following query:

db.pool.connect((err, client) => {

      // delete query
      const deleteQuery = "DELETE FROM images WHERE cloudinary_id = $1";
      const deleteValue = [cloudinary_id];

})
Enter fullscreen mode Exit fullscreen mode
  • Execute the query with the following code underneath it:

// execute delete query
      client.query(deleteQuery, deleteValue)
      .then((deleteResult) => {
        response.status(200).send({
          message: "Image Deleted Successfully!",
          deleteResult
        });
      }).catch((e) => {
        response.status(500).send({
          message: "Image Couldn't be Deleted!",
          e
        });
      });

Enter fullscreen mode Exit fullscreen mode

So our API should look like this:


// delete image
app.delete("/delete-image/:cloudinary_id", (request, response) => {
  // unique ID
  const { cloudinary_id } = request.params;

  // delete image from cloudinary first
  cloudinary.uploader
    .destroy(cloudinary_id)

    // delete image record from postgres also
    .then(() => {
      db.pool.connect((err, client) => {

      // delete query
      const deleteQuery = "DELETE FROM images WHERE cloudinary_id = $1";
      const deleteValue = [cloudinary_id];

      // execute delete query
      client
        .query(deleteQuery, deleteValue)
        .then((deleteResult) => {
          response.status(200).send({
            message: "Image Deleted Successfully!",
            deleteResult,
          });
        })
        .catch((e) => {
          response.status(500).send({
            message: "Image Couldn't be Deleted!",
            e,
          });
        });
      })
    })
    .catch((error) => {
      response.status(500).send({
        message: "Failure",
        error,
      });
    });
});

Enter fullscreen mode Exit fullscreen mode

The time has arrived for us to put our API to the test.

The following is my cloudinary media library with two images I uploaded already. Take note of their unique ID (public_id). We discussed this in the previous tutorials.

Alt Text

If you don't already have that, please use the persist-image API to upload some images.

Now let's proceed to postman

Alt Text

Notice, the unique ID as it matches one of the image in my cloudinary media library.

From the output, we executed the DELETE command and that deleted one ROW from our image TABLE in our database.

Now this is my media library with one of the images remaining:

Alt Text

Walahhhh... We are now able to get rid of an image.

Do take a break if you desire one. ✌🏾

Coffee Break

If you are ready, I am ready to update images

Update Image API

  • Below the delete-image API, let's start creating the update-image API with the following code:

// update image
app.put("/update-image/:cloudinary_id", (request, response) => {

});

All codes will live in there.

Enter fullscreen mode Exit fullscreen mode
  • Collect the unique cloudinary ID and new image details from the user with the following code:

// unique ID
  const { cloudinary_id } = request.params;

// collected image from a user
  const data = {
    title: request.body.title,
    image: request.body.image,
  };

Enter fullscreen mode Exit fullscreen mode
  • Delete the image from cloudinary with the following code

// delete image from cloudinary first
  cloudinary.uploader
    .destroy(cloudinary_id)
      // upload image here
    .then()
    .catch((error) => {
      response.status(500).send({
        message: "failed",
        error,
      });
    });

Enter fullscreen mode Exit fullscreen mode
  • Next, upload another image to cloudinary. To do that, enter the following code into the then block

() => {
      cloudinary.uploader
        .upload(data.image)
        .then()
        .catch((err) => {
          response.status(500).send({
            message: "failed",
            err,
          });
        });
    }

Enter fullscreen mode Exit fullscreen mode
  • Now let's replace our initial record with the new image details. Replace the content of the then block with the following:

(result) => {
          db.pool.connect((err, client) => {

            // update query
            const updateQuery =
              "UPDATE images SET title = $1, cloudinary_id = $2, image_url = $3 WHERE cloudinary_id = $4";
            const value = [
              data.title,
              result.public_id,
              result.secure_url,
              cloudinary_id,
            ];
          });
        }

Enter fullscreen mode Exit fullscreen mode
  • We execute the query using the following code just beneath the query declaration

// execute query
            client
              .query(updateQuery, value)
              .then(() => {

                // send success response
                response.status(201).send({
                  status: "success",
                  data: {
                    message: "Image Updated Successfully"
                  },
                });
              })
              .catch((e) => {
                response.status(500).send({
                  message: "Update Failed",
                  e,
                });
              });

Enter fullscreen mode Exit fullscreen mode

At this point, this is what I have


// update image
app.put("/update-image/:cloudinary_id", (request, response) => {
  // unique ID
  const { cloudinary_id } = request.params;

  // collected image from a user
  const data = {
    title: request.body.title,
    image: request.body.image,
  };

    // delete image from cloudinary first
    cloudinary.uploader
      .destroy(cloudinary_id)

      // upload image here
      .then(() => {
        cloudinary.uploader
          .upload(data.image)

          // update the database here
          .then((result) => {
            db.pool.connect((err, client) => {
            // update query
            const updateQuery =
              "UPDATE images SET title = $1, cloudinary_id = $2, image_url = $3 WHERE cloudinary_id = $4";
            const value = [
              data.title,
              result.public_id,
              result.secure_url,
              cloudinary_id,
            ];

            // execute query
            client
              .query(updateQuery, value)
              .then(() => {

                // send success response
                response.status(201).send({
                  status: "success",
                  data: {
                    message: "Image Updated Successfully"
                  },
                });
              })
              .catch((e) => {
                response.status(500).send({
                  message: "Update Failed",
                  e,
                });
              });
            });
          })
          .catch((err) => {
            response.status(500).send({
              message: "failed",
              err,
            });
          });
      })
      .catch((error) => {
        response.status(500).send({
          message: "failed",
          error,
        });
      });

});

Enter fullscreen mode Exit fullscreen mode

It's Testing Time!!!

This is my postman in the image below:

Alt Text

Take note of the unique cloudinary ID which matches the image left in my cloudinary media library.

Now take a look at my cloudinary media library in the image that follows:

Alt Text

Take note of the new image replacing the initial one in my media library above

Also, see that the unique clodinary ID matches that in my database with the new title. See image below:

Alt Text

Yayeh!!!

You did awesomely great!!! πŸ’ͺ

We just completed a CRUD application with nodejs, cloudinary and postgresql!!!

Conclusion

We have been able to complete what we started a couple of months ago - A CRUD App. If you started from the beginning with us, then you will see that we started from nothing but now we are dinning with not just nodejs but cloudinary and postgres.

All codes can be found here

GitHub logo EBEREGIT / server-tutorial

This is a tutorial was to teach how to create a simple, secure and robust nodejs server but we have expanded our scope to cloudinary and postgres

Server-tutorial

This is a tutorial was to teach how to create a simple, secure and robust nodejs server but we have expanded our scope to cloudinary and postgres

Full details on how to build out this server is found here.

Full details on how to upload images to cloudinary using nodejs is found here.

Full details on how to persist and retrieve images to cloudinary using nodejs and postgres is found here.

Full details on how to delete and update images to cloudinary using nodejs and postgres is found here.

Full details on Nodejs Code Structure Optimization With Express Routing is found here.

Dependences

SETTING UP

  • Fork this repository
  • Clone the repositury to your machine
  • Open up a terminal
  • Navigate into the project directory
  • Run npm install to install all needed dependencies
  • Run nodemon index to spin…




Please keep up the good learning!!!

Thumbs Up

You will notice that our App.js file is now too long and we are getting lost in our code. That is going to be fixed in the next article where we will be doing something nice on Nodejs Code Structure Optimization With Express Routing.

If you have questions, comments or suggestions, please drop them in the comment section.

You can also follow and message me on social media platforms.

Twitter | LinkedIn | Github

Thank You For Your Time.

Top comments (0)