Skip to content

Commit

Permalink
feat: Adds handlers for DELETE for user accounts (#38)
Browse files Browse the repository at this point in the history
  • Loading branch information
saltiyazan committed Jul 5, 2024
1 parent 7057751 commit 412bb63
Show file tree
Hide file tree
Showing 2 changed files with 38 additions and 0 deletions.
22 changes: 22 additions & 0 deletions internal/api/handlers.go
Original file line number Diff line number Diff line change
Expand Up @@ -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()
Expand Down Expand Up @@ -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)
Expand Down
16 changes: 16 additions & 0 deletions internal/api/handlers_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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) {
Expand Down

0 comments on commit 412bb63

Please sign in to comment.