67 lines
1.6 KiB
Go
67 lines
1.6 KiB
Go
package user
|
|
|
|
import (
|
|
"RenewCMS/api/pkg/apperr"
|
|
"RenewCMS/api/pkg/response"
|
|
domainUser "RenewCMS/internal/domain/user"
|
|
"RenewCMS/internal/infrastructure/useCases"
|
|
"errors"
|
|
"net/http"
|
|
"strconv"
|
|
"strings"
|
|
)
|
|
|
|
type LookupHandler struct {
|
|
LookupUseCase *useCases.LookupUserNamesUseCase
|
|
}
|
|
|
|
type userNameResponse struct {
|
|
ID uint32 `json:"id"`
|
|
DisplayName string `json:"display_name"`
|
|
}
|
|
|
|
func NewLookupHandler(lookup *useCases.LookupUserNamesUseCase) *LookupHandler {
|
|
return &LookupHandler{LookupUseCase: lookup}
|
|
}
|
|
|
|
func parseLookupIDs(raw string) ([]uint32, bool) {
|
|
if raw == "" {
|
|
return nil, false
|
|
}
|
|
if strings.Count(raw, ",")+1 > domainUser.MaxLookupIDs {
|
|
return nil, false
|
|
}
|
|
parts := strings.Split(raw, ",")
|
|
ids := make([]uint32, 0, len(parts))
|
|
for _, part := range parts {
|
|
id, err := strconv.ParseUint(part, 10, 32)
|
|
if err != nil {
|
|
return nil, false
|
|
}
|
|
ids = append(ids, uint32(id))
|
|
}
|
|
return ids, true
|
|
}
|
|
|
|
func (h *LookupHandler) Lookup(w http.ResponseWriter, r *http.Request) {
|
|
ids, ok := parseLookupIDs(r.URL.Query().Get("ids"))
|
|
if !ok {
|
|
http.Error(w, apperr.BodyErrorMessage, http.StatusBadRequest)
|
|
return
|
|
}
|
|
names, err := h.LookupUseCase.Lookup(ids)
|
|
if errors.Is(err, domainUser.ErrInvalidLookup) {
|
|
http.Error(w, apperr.BodyErrorMessage, http.StatusBadRequest)
|
|
return
|
|
}
|
|
if err != nil {
|
|
http.Error(w, "Internal server error", http.StatusInternalServerError)
|
|
return
|
|
}
|
|
items := make([]userNameResponse, 0, len(names))
|
|
for _, name := range names {
|
|
items = append(items, userNameResponse{ID: name.ID, DisplayName: name.DisplayName})
|
|
}
|
|
response.WriteJSON(w, http.StatusOK, items)
|
|
}
|