Skip to content

Commit

Permalink
feat: Change response add role object to users response
Browse files Browse the repository at this point in the history
  • Loading branch information
trianggianggara committed Jul 11, 2024
1 parent a9804d3 commit 5d747e1
Show file tree
Hide file tree
Showing 2 changed files with 49 additions and 0 deletions.
10 changes: 10 additions & 0 deletions internal/delivery/api/user/user.go
Original file line number Diff line number Diff line change
Expand Up @@ -17,11 +17,21 @@ func NewDelivery(f factory.Factory) *delivery {
}

func (h *delivery) Route(g *echo.Group) {
g.GET("", h.Get)
g.GET("/:id", h.GetByID)
g.GET("/", h.GetByEmail)
g.POST("/", h.Create)
}

func (h *delivery) Get(c echo.Context) error {
result, err := h.Factory.Usecase.User.Find(c.Request().Context())
if err != nil {
return res.ErrorResponse(err).Send(c)
}

return res.CustomSuccessBuilder(200, result, "Get all users success").Send(c)
}

func (h *delivery) GetByID(c echo.Context) error {
payload := new(dto.ByIDRequest)
if err := c.Bind(payload); err != nil {
Expand Down
39 changes: 39 additions & 0 deletions internal/usecase/user_usecase.go
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,37 @@ func NewUserUsecase(f repository.Factory) *UserUsecase {
return &UserUsecase{f}
}

func (u *UserUsecase) Find(ctx context.Context) ([]dto.UserResponse, error) {
var result []dto.UserResponse

users, err := u.RepositoryFactory.UserRepository.Find(ctx)
if err != nil {
u.RepositoryFactory.Log.Warnf("Failed find all users: %+v", err)
return result, err
}

roles, err := u.RepositoryFactory.RoleRepository.Find(ctx)
if err != nil {
u.RepositoryFactory.Log.Warnf("Failed find all roles: %+v", err)
return result, err
}

roleMap := make(map[string]model.RoleModel)
for _, role := range roles {
roleMap[role.ID] = role
}

for _, user := range users {
roleData := roleMap[user.RoleID]
user.Role = &roleData
result = append(result, dto.UserResponse{
Data: user,
})
}

return result, nil
}

func (u *UserUsecase) FindByID(ctx context.Context, payload dto.ByIDRequest) (dto.UserResponse, error) {
var result dto.UserResponse

Expand All @@ -25,6 +56,14 @@ func (u *UserUsecase) FindByID(ctx context.Context, payload dto.ByIDRequest) (dt
return result, err
}

role, err := u.RepositoryFactory.RoleRepository.FindByID(ctx, data.RoleID)
if err != nil {
u.RepositoryFactory.Log.Warnf("Failed find all roles: %+v", err)
return result, err
}

data.Role = role

result = dto.UserResponse{
Data: *data,
}
Expand Down

0 comments on commit 5d747e1

Please sign in to comment.