tsk-11: Added endpoint to get Contact (#17)

Closes #11

Reviewed-on: phoenix/textsender-api#17
Co-authored-by: phoenix <kundeng00@pm.me>
Co-committed-by: phoenix <kundeng00@pm.me>
This commit is contained in:
phoenix
2025-11-06 20:09:52 +00:00
committed by phoenix
parent 507eb9eb09
commit acf414c876
5 changed files with 116 additions and 1 deletions
+82
View File
@@ -20,6 +20,11 @@ type AddContactResponse struct {
Data []contact.Contact `json:"data"`
}
type GetContactResponse struct {
Message string `json:"message"`
Data []contact.Contact `json:"data"`
}
type ContactHandler struct {
ContactStore store.ContactStore
}
@@ -70,3 +75,80 @@ func (c *ContactHandler) AddContact(w http.ResponseWriter, r *http.Request) {
RespondWithJSON(w, statusCode, &resp)
}
func (c *ContactHandler) GetContact(w http.ResponseWriter, r *http.Request) {
if r.Method != http.MethodGet {
fmt.Println("Method:", r.Method)
http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)
return
}
var id, userId uuid.UUID
queryParams := r.URL.Query()
// Check if parameter exists
if _, exists := queryParams["id"]; !exists {
if _, exists := queryParams["user_id"]; !exists {
fmt.Fprintf(w, "Name parameter not provided")
http.Error(w, "Query params", http.StatusBadRequest)
return
} else {
var err error
userId, err = uuid.Parse(queryParams.Get("user_id"))
if err != nil {
fmt.Fprintf(w, "Name parameter exists: %s", userId)
}
}
} else {
var err error
idTmp := queryParams.Get("id")
id, err = uuid.Parse(idTmp)
if err != nil {
fmt.Println("Error:", err)
http.Error(w, "Error parsing Id", http.StatusBadRequest)
return
}
}
var statusCode int
var resp GetContactResponse
ctx := r.Context()
if id != uuid.Nil {
fmt.Println("Checking with Id")
if con, err := c.ContactStore.GetContactByID(ctx, id); err == nil {
statusCode = http.StatusOK
resp.Message = "Successful"
resp.Data = append(resp.Data, *con)
} else {
statusCode = http.StatusInternalServerError
resp.Message = err.Error()
}
} else if userId != uuid.Nil {
fmt.Println("Checking with User Id")
if contacts, err := c.ContactStore.GetAllContacts(ctx); err == nil {
for _, con := range contacts {
if con.UserId == userId {
resp.Data = append(resp.Data, *con)
}
}
if len(resp.Data) > 0 {
statusCode = http.StatusOK
resp.Message = "Successful"
} else {
statusCode = http.StatusNotFound
resp.Message = "Contact not found"
}
} else {
statusCode = http.StatusInternalServerError
resp.Message = err.Error()
}
} else {
statusCode = http.StatusBadRequest
resp.Message = "Invalid query parameter"
}
RespondWithJSON(w, statusCode, &resp)
}