7.12: Deleting Photos

We've spent a lot of time on uploading and displaying photos - let's delete them!!

Deleting Photos in the API

First, let's add a method in our PhotoService for deleting photos from Cloudinary. We already have a generic method for deleting entities from the database, so we don't have to write one in our PhotoService.

In IPhotoService.cs add the following method signatures:

object DeletePhotoFromCloudinary(string publicId);
Task<Photo> GetPhotoEntity(int id);

We're adding another GetPhoto method - previously, we were returning a DTO - this time we need to return an actual entity so we can delete it from the database.

Now, let's implement them in our PhotoService concrete class:

public async Task<Photo> GetPhotoEntity(int id)
{
    return await _context.Photos.FirstOrDefaultAsync(p => p.Id == id);
}

public object DeletePhotoFromCloudinary(string publicId)
{
    var deleteParams = new DeletionParams(publicId);
    return _cloudinary.Destroy(deleteParams).Result;
}

In the .API project, open up the PhotosController and add a new method called DeletePhoto()

Test out the API to see if you're able to successfully delete a photo.

Get a fresh token from the /auth/login endpoint.

Send a DELETE request to http://localhost:5000/api/users/{userId}/photos/{photoId}

You should get a 200 OK response:

DeletePhotoPostman

Deleting Photos in Angular

First, we'll add a method to the user.service.ts file:

Now, we can use it in the photo-editor.component.ts:

And, we can use it in the 'photo-editor.component.html` file:

Wrap-up

Great job! Everything should be working now. Feel free to play around in the app a bit and try uploading and deleting photos and see if you find any bugs. If you do - try to figure out how to fix it.

We've done quite a bit in this module and we've learned a lot!

Last updated