DEV Community

Cover image for "ChatGPT: The problem-solving pro in a NodeJs app"
Abayomi Ogunnusi
Abayomi Ogunnusi

Posted on

 

"ChatGPT: The problem-solving pro in a NodeJs app"

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


Here's the instruction we gave ChatGPT
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);
  }
};
Enter fullscreen mode Exit fullscreen mode

Here is ChatGPT's response
// 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);

Enter fullscreen mode Exit fullscreen mode

Solution line that fixed our problem.
 await cloudinary.uploader.destroy(provider.frontImage.split('/').pop().split('.')[0]);
Enter fullscreen mode Exit fullscreen mode

As a curious cat, I analyzed the code and logged its response.
//....
    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]);
//...
Enter fullscreen mode Exit fullscreen mode
This is the outcome:
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
Enter fullscreen mode Exit fullscreen mode
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.

Top comments (3)

Collapse
 
chideraike profile image
Chidera

Interesting solution it came up with

Collapse
 
drsimplegraffiti profile image
Abayomi Ogunnusi

Yes it was really interesting

Collapse
 
fredabod profile image
FredAbod

Wizardry AI😎😊😎