From 412bb63dbe9f8176d7125de3c3196e180a5e3e90 Mon Sep 17 00:00:00 2001 From: saltiyazan Date: Fri, 5 Jul 2024 10:15:22 +0200 Subject: [PATCH] feat: Adds handlers for DELETE for user accounts (#38) --- internal/api/handlers.go | 22 ++++++++++++++++++++++ internal/api/handlers_test.go | 16 ++++++++++++++++ 2 files changed, 38 insertions(+) diff --git a/internal/api/handlers.go b/internal/api/handlers.go index 12a284f..d1fc33f 100644 --- a/internal/api/handlers.go +++ b/internal/api/handlers.go @@ -34,6 +34,7 @@ func NewGoCertRouter(env *Environment) http.Handler { apiV1Router.HandleFunc("GET /accounts/{id}", GetUserAccount(env)) apiV1Router.HandleFunc("GET /accounts", GetUserAccounts(env)) apiV1Router.HandleFunc("POST /accounts", PostUserAccount(env)) + apiV1Router.HandleFunc("DELETE /accounts/{id}", DeleteUserAccount(env)) m := metrics.NewMetricsSubsystem(env.DB) frontendHandler := newFrontendFileServer() @@ -360,6 +361,27 @@ func PostUserAccount(env *Environment) http.HandlerFunc { } } +// DeleteUserAccount handler receives an id as a path parameter, +// deletes the corresponding User Account, and returns a http.StatusNoContent on success +func DeleteUserAccount(env *Environment) http.HandlerFunc { + return func(w http.ResponseWriter, r *http.Request) { + id := r.PathValue("id") + insertId, err := env.DB.DeleteUser(id) + if err != nil { + if errors.Is(err, certdb.ErrIdNotFound) { + logErrorAndWriteResponse(err.Error(), http.StatusNotFound, w) + return + } + logErrorAndWriteResponse(err.Error(), http.StatusInternalServerError, w) + return + } + w.WriteHeader(http.StatusAccepted) + if _, err := w.Write([]byte(strconv.FormatInt(insertId, 10))); err != nil { + logErrorAndWriteResponse(err.Error(), http.StatusInternalServerError, w) + } + } +} + // logErrorAndWriteResponse is a helper function that logs any error and writes it back as an http response func logErrorAndWriteResponse(msg string, status int, w http.ResponseWriter) { errMsg := fmt.Sprintf("error: %s", msg) diff --git a/internal/api/handlers_test.go b/internal/api/handlers_test.go index 4e30dbb..d85bfe0 100644 --- a/internal/api/handlers_test.go +++ b/internal/api/handlers_test.go @@ -441,6 +441,22 @@ func TestGoCertUsersHandlers(t *testing.T) { response: "error: Username is required", status: http.StatusBadRequest, }, + { + desc: "Delete user success", + method: "DELETE", + path: "/api/v1/accounts/2", + data: invalidUser, + response: "1", + status: http.StatusAccepted, + }, + { + desc: "Delete user failure", + method: "DELETE", + path: "/api/v1/accounts/2", + data: invalidUser, + response: "error: id not found", + status: http.StatusNotFound, + }, } for _, tC := range testCases { t.Run(tC.desc, func(t *testing.T) {