tsk-58: Update names of Contact endpoint (#67)
Closes #58 Reviewed-on: phoenix/textsender-api#67 Co-authored-by: phoenix <kundeng00@pm.me> Co-committed-by: phoenix <kundeng00@pm.me>
This commit is contained in:
@@ -179,3 +179,68 @@ func (c *ContactHandler) GetContact(w http.ResponseWriter, r *http.Request) {
|
||||
|
||||
RespondWithJSON(w, statusCode, &resp)
|
||||
}
|
||||
|
||||
type UpdateNameRequest struct {
|
||||
Nickname *string `json:"nickname,omitempty"`
|
||||
Firstname *string `json:"first_name,omitempty"`
|
||||
Lastname *string `json:"last_name,omitempty"`
|
||||
ContactId uuid.UUID `json:"contact_id"`
|
||||
UserId uuid.UUID `json:"user_id"`
|
||||
}
|
||||
|
||||
type UpdateNameResponse struct {
|
||||
Message string `json:"message"`
|
||||
Data []contact.Contact `json:"data"`
|
||||
}
|
||||
|
||||
// UpdateName godoc
|
||||
// @Summary Update names of Contact
|
||||
// @Description Update the first, last, or nickname of a Contact (requires JWT)
|
||||
// @Tags contacts
|
||||
// @Accept json
|
||||
// @Produce json
|
||||
// @Security BearerAuth
|
||||
// @Param request body UpdateNameRequest true "Data to update contact's names"
|
||||
// @Success 200 {object} UpdateNameResponse
|
||||
// @Failure 400 {object} UpdateNameResponse
|
||||
// @Failure 500 {object} UpdateNameResponse
|
||||
// @Router /contact/update [patch]
|
||||
func (c *ContactHandler) UpdateName(w http.ResponseWriter, r *http.Request) {
|
||||
var req UpdateNameRequest
|
||||
if err := ExtractFromRequest(r, &req); err != nil {
|
||||
http.Error(w, "Invalid JSON: "+err.Error(), http.StatusBadRequest)
|
||||
}
|
||||
defer r.Body.Close()
|
||||
|
||||
var statusCode int
|
||||
var resp UpdateNameResponse
|
||||
|
||||
if req.UserId == uuid.Nil {
|
||||
statusCode = http.StatusBadRequest
|
||||
resp.Message = "User Id not provided"
|
||||
} else if req.ContactId == uuid.Nil {
|
||||
statusCode = http.StatusBadRequest
|
||||
resp.Message = "Contact Id not provided"
|
||||
} else if req.Firstname == nil && req.Lastname == nil && req.Nickname == nil {
|
||||
statusCode = http.StatusBadRequest
|
||||
resp.Message = "No name provided"
|
||||
} else {
|
||||
ctx := r.Context()
|
||||
if con, err := c.ContactStore.GetContactByID(ctx, req.ContactId); err != nil {
|
||||
resp.Message = err.Error()
|
||||
statusCode = http.StatusInternalServerError
|
||||
} else {
|
||||
if affectedRows, err := c.ContactStore.UpdateNames(ctx, con, req.Firstname, req.Lastname, req.Nickname); err != nil {
|
||||
statusCode = http.StatusInternalServerError
|
||||
resp.Message = err.Error()
|
||||
} else {
|
||||
log.Println("Updated", affectedRows, "rows")
|
||||
statusCode = http.StatusOK
|
||||
resp.Message = "Successful"
|
||||
resp.Data = append(resp.Data, *con)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
RespondWithJSON(w, statusCode, &resp)
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user