feat: move user dto outside

This commit is contained in:
2025-06-04 12:46:24 +02:00
parent 81659181e4
commit c6998f33e1
3 changed files with 43 additions and 29 deletions

View File

@ -4,27 +4,14 @@ import (
"encoding/json"
"log"
"net/http"
"time"
"gitea.local/admin/hspguard/internal/repository"
"gitea.local/admin/hspguard/internal/types"
"gitea.local/admin/hspguard/internal/web"
"github.com/google/uuid"
)
type UserDTO struct {
ID uuid.UUID `json:"id"`
Email string `json:"email"`
FullName string `json:"full_name"`
IsAdmin bool `json:"is_admin"`
CreatedAt *time.Time `json:"created_at"`
UpdatedAt *time.Time `json:"updated_at"`
LastLogin *time.Time `json:"last_login"`
PhoneNumber *string `json:"phone_number"`
ProfilePicture *string `json:"profile_picture"`
}
func NewUserDTO(row *repository.User) UserDTO {
return UserDTO{
func NewUserDTO(row *repository.User) types.UserDTO {
return types.UserDTO{
ID: row.ID,
Email: row.Email,
FullName: row.FullName,
@ -45,15 +32,23 @@ func (h *AdminHandler) GetUsers(w http.ResponseWriter, r *http.Request) {
return
}
var response []UserDTO
type Response struct {
Items []types.UserDTO `json:"items"`
Count int `json:"count"`
}
var items []types.UserDTO
for _, user := range users {
response = append(response, NewUserDTO(&user))
items = append(items, NewUserDTO(&user))
}
encoder := json.NewEncoder(w)
if err := encoder.Encode(&response); err != nil {
if err := encoder.Encode(&Response{
Items: items,
Count: len(items),
}); err != nil {
web.Error(w, "failed to send response", http.StatusInternalServerError)
}
}

View File

@ -160,16 +160,16 @@ func (h *AuthHandler) getProfile(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json")
if err := json.NewEncoder(w).Encode(map[string]any{
"id": user.ID.String(),
"full_name": user.FullName,
"email": user.Email,
"phone_number": user.PhoneNumber,
"isAdmin": user.IsAdmin,
"last_login": user.LastLogin,
"profile_picture": user.ProfilePicture,
"updated_at": user.UpdatedAt,
"created_at": user.CreatedAt,
if err := json.NewEncoder(w).Encode(types.UserDTO{
ID: user.ID,
FullName: user.FullName,
Email: user.Email,
PhoneNumber: user.PhoneNumber,
IsAdmin: user.IsAdmin,
LastLogin: user.LastLogin,
ProfilePicture: user.ProfilePicture,
UpdatedAt: user.UpdatedAt,
CreatedAt: user.CreatedAt,
}); err != nil {
web.Error(w, "failed to encode user profile", http.StatusInternalServerError)
}

19
internal/types/user.go Normal file
View File

@ -0,0 +1,19 @@
package types
import (
"time"
"github.com/google/uuid"
)
type UserDTO struct {
ID uuid.UUID `json:"id"`
Email string `json:"email"`
FullName string `json:"full_name"`
IsAdmin bool `json:"is_admin"`
CreatedAt *time.Time `json:"created_at"`
UpdatedAt *time.Time `json:"updated_at"`
LastLogin *time.Time `json:"last_login"`
PhoneNumber *string `json:"phone_number"`
ProfilePicture *string `json:"profile_picture"`
}