"ChatGPT: The problem-solving pro in a NodeJs app"
Tags: ai, javascript, node, cloud
Published: 2023-01-19 12:18:11

#### Unleashing the power of technology.

My colleague and I tackled a tricky task of uploading new images to Cloudinary while simultaneously deleting the previous ones using public id. 

Despite our efforts, success eluded us. But, with a stroke of brilliance, we decided to enlist the help of our trusty AI friend ChatGPT and voila! Problem solved!
![viola](https://media.giphy.com/media/8P1oO2JbrZK2uSYnL6/giphy.gif)


---

##### Here's the instruction we gave ChatGPT
```javascript
Revamp the code below to delete previous images from cloudinary before updating new ones


// upload front and back images of okada rider
exports.uploadOkadaImages = async (req, res, next) => {
  try {
    const { id } = req.user;

    // verify mongoose id
    if (!mongoose.Types.ObjectId.isValid(id))
      return errorResMsg(res, 400, "Invalid provider id");

    const provider = await Provider.findById({ _id: id });

    if (!provider) return errorResMsg(res, 404, "Provider not found");

    if (!req.files) return errorResMsg(res, 400, "Please upload a photo");
    console.log(req.files);

    let images = await Promise.all(
      req.files.map(async (file) => {
        let image = await cloudinary.uploader.upload(file.path);
        return image.secure_url;
      })
    );

    provider.frontImage = images[0];
    provider.backImage = images[1];

    await provider.save();
    const dataInfo = {
      message: "Profile photo updated successfully",
    };

    return successResMsg(res, 200, dataInfo);
  } catch (error) {
    next(error);
  }
};
```
---

##### Here is ChatGPT's response
```javascript
// verify mongoose id
if (!mongoose.Types.ObjectId.isValid(id))
  return errorResMsg(res, 400, "Invalid provider id");

const provider = await Provider.findById({ _id: id });

if (!provider) return errorResMsg(res, 404, "Provider not found");

if (!req.files) return errorResMsg(res, 400, "Please upload a photo");
console.log(req.files);

// delete previous images from Cloudinary
if (provider.frontImage) {
  await cloudinary.uploader.destroy(provider.frontImage.split('/').pop().split('.')[0]);
}
if (provider.backImage) {
  await cloudinary.uploader.destroy(provider.backImage.split('/').pop().split('.')[0]);
}

let images = await Promise.all(
  req.files.map(async (file) => {
    let image = await cloudinary.uploader.upload(file.path);
    return image.secure_url;
  })
);

provider.frontImage = images[0];
provider.backImage = images[1];

await provider.save();
const dataInfo = {
  message: "Profile photo updated successfully",
};

return successResMsg(res, 200, dataInfo);

```

---

##### Solution line that fixed our problem.
```javascript
 await cloudinary.uploader.destroy(provider.frontImage.split('/').pop().split('.')[0]);
```

---

##### As a curious cat, I analyzed the code and logged its response.
```javascript
//....
    if (!provider) return errorResMsg(res, 404, "Provider not found");

    if (!req.files) return errorResMsg(res, 400, "Please upload a photo");
    console.log(provider.frontImage);
    console.log(provider.frontImage.split("/"));
    console.log(provider.frontImage.split("/").pop());
    console.log(provider.frontImage.split("/").pop().split("."));
  console.log(provider.frontImage.split("/").pop().split(".")[0]);
//...
```

##### This is the outcome:
```javascript
https://res.cloudinary.com/drsimple/image/upload/v1674127038/hi7ysnojodqcelrpdrud.jpg
[
  'https:',
  '',
  'res.cloudinary.com',
  'drsimple',
  'image',
  'upload',
  'v1674127038',
  'hi7ysnojodqcelrpdrud.jpg'
]
hi7ysnojodqcelrpdrud.jpg
[ 'hi7ysnojodqcelrpdrud', 'jpg' ]
hi7ysnojodqcelrpdrud
```
 
##### Code explanation:

_The specific picture that it wants to delete is found by going through the provider's front image variable, which contains the image url of the front image. 
It splits the url by '/' and takes the last part after the last '/', which is the `public_id` of the image. Then it splits this by '.' and takes the first part which is the public_id of the image, and then it uses that `public_id` to delete that image from cloudinary._


---

#### Conclusion
As software engineers, we can embrace tools like ChatGPT and other AI technologies to speed up our problem solving, thought process, and overall performance. These tools can assist us in quickly understanding and analyzing code, providing explanations and solutions to problems, and streamlining our workflow. By incorporating AI technology into our work processes, we can not only improve our efficiency but also gain insights and perspectives that may not have been previously considered.

 ⚠ However, it's important to keep in mind that AI should be used as an aid and not a replacement for human intelligence, and that the results of these tools should be validated and reviewed by humans before making any decisions.