role service

master
nima 2024-06-17 19:04:55 +03:30
parent 3e301f7387
commit d70d2b1621
1 changed files with 87 additions and 0 deletions

87
services/role.go 100644
View File

@ -0,0 +1,87 @@
package services
import (
"net/http"
"netina/commands"
cm "netina/models/commands"
"netina/queries"
Role_repository "netina/repositories/role"
"netina/validation"
"strconv"
"github.com/labstack/echo/v4"
)
type RoleService struct {
CommandRepo Role_repository.RoleCommandRepository
QueryRepo Role_repository.RoleQueryRepository
}
func (s *RoleService) CreateRole(c echo.Context) error {
role := new(cm.CreateRoleCommand)
if err := c.Bind(role); err != nil {
return c.JSON(http.StatusBadRequest, map[string]string{"error": "Invalid request payload"})
}
if err := validation.ValidateStruct(role); err != nil {
return c.JSON(http.StatusBadRequest, map[string]string{"error": err.Error()})
}
handler := commands.CreateRoleHandler{Repository: s.CommandRepo}
if err := handler.Handle(*role); err != nil {
return c.JSON(http.StatusInternalServerError, map[string]string{"error": err.Error()})
}
return c.JSON(http.StatusCreated, role)
}
func (s *RoleService) GetRole(c echo.Context) error {
id, err := strconv.Atoi(c.Param("id"))
if err != nil {
return c.JSON(http.StatusBadRequest, map[string]string{"error": "Invalid role ID"})
}
handler := queries.GetRoleHandler{Repository: s.QueryRepo}
role, err := handler.Handle(uint(id))
if err != nil {
return c.JSON(http.StatusNotFound, map[string]string{"error": err.Error()})
}
return c.JSON(http.StatusOK, role)
}
func (s *RoleService) UpdateRole(c echo.Context) error {
id, err := strconv.Atoi(c.Param("id"))
if err != nil {
return c.JSON(http.StatusBadRequest, map[string]string{"error": "Invalid role ID"})
}
role := new(cm.UpdateRoleCommand)
if err := c.Bind(role); err != nil {
return c.JSON(http.StatusBadRequest, map[string]string{"error": "Invalid request payload"})
}
if err := validation.ValidateStruct(role); err != nil {
return c.JSON(http.StatusBadRequest, map[string]string{"error": err.Error()})
}
handler := commands.UpdateRoleHandler{Repository: s.CommandRepo}
updatedRole, err := handler.Handle(uint(id), *role)
if err != nil {
return c.JSON(http.StatusInternalServerError, map[string]string{"error": err.Error()})
}
return c.JSON(http.StatusOK, updatedRole)
}
func (s *RoleService) RemoveRole(c echo.Context) error {
id, err := strconv.Atoi(c.Param("id"))
if err != nil {
return c.JSON(http.StatusBadRequest, map[string]string{"error": "Invalid Role ID"})
}
handler := commands.RemoveRoleHandler{Repository: s.CommandRepo}
if err := handler.Handle(uint(id)); err != nil {
return c.JSON(http.StatusInternalServerError, map[string]string{"error": err.Error()})
}
return c.NoContent(http.StatusNoContent)
}