diff --git a/cmd/api/movies.go b/cmd/api/movies.go index 21cadee..e8b5fe2 100644 --- a/cmd/api/movies.go +++ b/cmd/api/movies.go @@ -150,3 +150,30 @@ func (app *application) updateMovieHandler(w http.ResponseWriter, r *http.Reques app.serverErrorResponse(w, r, err) } } + +func (app *application) deleteMovieHandler(w http.ResponseWriter, r *http.Request) { + // Extract the movie ID from the URL + id, err := app.readIDParam(r) + if err != nil { + app.notFoundResponse(w, r) + return + } + + // Delete the movie from the database, sending a 404 Not Found response to the client if there isn't a matching record + err = app.models.Movies.Delete(id) + if err != nil { + switch { + case errors.Is(err, data.ErrRecordNotFound): + app.notFoundResponse(w, r) + default: + app.serverErrorResponse(w, r, err) + } + return + } + + // Return a 200 OK status code along with a success message + err = app.writeJSON(w, http.StatusOK, envelope{"message": "movie successfully deleted"}, nil) + if err != nil { + app.serverErrorResponse(w, r, err) + } +} diff --git a/cmd/api/routes.go b/cmd/api/routes.go index 63f877d..17c2bac 100644 --- a/cmd/api/routes.go +++ b/cmd/api/routes.go @@ -25,6 +25,7 @@ func (app *application) routes() http.Handler { router.HandlerFunc(http.MethodPost, "/v1/movies", app.createMovieHandler) router.HandlerFunc(http.MethodGet, "/v1/movies/:id", app.showMovieHandler) router.HandlerFunc(http.MethodPut, "/v1/movies/:id", app.updateMovieHandler) + router.HandlerFunc(http.MethodDelete, "/v1/movies/:id", app.deleteMovieHandler) // Return the httprouter instance. // Wrap the router with the panic recovery middleware diff --git a/internal/data/movies.go b/internal/data/movies.go index 9506ab8..1a43c8c 100644 --- a/internal/data/movies.go +++ b/internal/data/movies.go @@ -131,5 +131,32 @@ func (m MovieModel) Update(movie *Movie) error { // Delete : Deleting a specific record from the movies table func (m MovieModel) Delete(id int64) error { + // Return an ErrRecordNotFound err if the movie ID is less than 1 + if id < 1 { + return ErrRecordNotFound + } + + // Construct the SQL query to delete the record + query := ` + DELETE FROM movies + WHERE id = $1` + + // Execute the SQL query using the Exec() method, passing in the id variable as the value for the placeholder parameter. The Exec() method returns a sql.Result object. + result, err := m.DB.Exec(query, id) + if err != nil { + return err + } + + // Call the RowsAffected() method on the sql.Result object to get the number of rows after by the query. + rowsAffected, err := result.RowsAffected() + if err != nil { + return err + } + + // If no rows were affected, we know that the movies table didn't contain a record with provided ID at the moment we tried to delete it. In that case we return an ErrRecordNotFound error + if rowsAffected == 0 { + return ErrRecordNotFound + } + return nil }