changed arhitecture

This commit is contained in:
2026-07-15 18:08:19 +05:00
parent 7e3a5cebcc
commit 585ba63bc2
95 changed files with 4985 additions and 1360 deletions

View File

@@ -0,0 +1,108 @@
package db
import (
"context"
"errors"
"fmt"
"strings"
"online-back/internal/identity/role"
"online-back/pkg/client/postgresql"
"online-back/pkg/logging"
"online-back/pkg/repository/genericrepo"
"github.com/jackc/pgx/v4"
)
type repository struct {
client postgresql.Client
generic *genericrepo.Repository[role.RoleDTO]
logger *logging.Logger
}
func NewRepository(client postgresql.Client, logger *logging.Logger) role.Repository {
return &repository{
client: client,
generic: genericrepo.New(client, "roles r", roleColumns, scanRole),
logger: logger,
}
}
const roleColumns = `r.id, r.code, r.name, r.guard_name, r.created_at, r.updated_at`
const roleReturningColumns = `id, code, name, guard_name, created_at, updated_at`
func (r *repository) List(ctx context.Context, filter role.ListFilter) (role.ListRoleDTO, error) {
whereClause, args := buildListQuery(filter)
items, count, err := r.generic.List(ctx, whereClause, args, filter.Page, filter.Limit, "id")
if err != nil {
return role.ListRoleDTO{}, err
}
return role.ListRoleDTO{Count: count, Roles: items}, nil
}
func buildListQuery(filter role.ListFilter) (whereClause string, args []interface{}) {
var conditions []string
if filter.RoleName != "" {
args = append(args, likePattern(filter.RoleName))
n := len(args)
conditions = append(conditions, fmt.Sprintf(`r.name ILIKE $%d`, n))
}
if len(conditions) == 0 {
return "", args
}
return " WHERE " + strings.Join(conditions, " AND "), args
}
func likePattern(term string) string {
term = strings.ReplaceAll(term, `\`, `\\`)
term = strings.ReplaceAll(term, `%`, `\%`)
term = strings.ReplaceAll(term, `_`, `\_`)
return "%" + term + "%"
}
func (r *repository) GetByID(ctx context.Context, id int64) (role.RoleDTO, error) {
return r.generic.GetByID(ctx, id)
}
func (r *repository) Create(ctx context.Context, dto role.CreateRoleDTO) (role.RoleDTO, error) {
query := fmt.Sprintf(`
INSERT INTO roles (code, name, guard_name)
VALUES ($1, $2, $3)
RETURNING %s`, roleReturningColumns)
return scanRole(r.client.QueryRow(ctx, query, dto.Code, dto.Name, dto.GuardName))
}
func (r *repository) Update(ctx context.Context, id int64, dto role.UpdateRoleDTO) (role.RoleDTO, error) {
query := fmt.Sprintf(`
UPDATE roles SET
code = $1, name = $2, guard_name = $3,
updated_at = (CURRENT_TIMESTAMP AT TIME ZONE 'UTC')
WHERE id = $4
RETURNING %s`, roleReturningColumns)
item, err := scanRole(r.client.QueryRow(ctx, query, dto.Code, dto.Name, dto.GuardName, id))
if errors.Is(err, pgx.ErrNoRows) {
return role.RoleDTO{}, err
}
return item, err
}
func (r *repository) Delete(ctx context.Context, id int64) error {
return r.generic.Delete(ctx, id)
}
func scanRole(row genericrepo.Scanner) (role.RoleDTO, error) {
var item role.RoleDTO
if err := row.Scan(
&item.Id, &item.Code, &item.Name, &item.GuardName, &item.CreatedAt, &item.UpdatedAt,
); err != nil {
return role.RoleDTO{}, err
}
return item, nil
}

View File

@@ -0,0 +1,35 @@
package role
import "time"
type RoleDTO struct {
Id int64 `json:"id"`
Code string `json:"code"`
Name string `json:"name"`
GuardName string `json:"guardName"`
CreatedAt time.Time `json:"createdAt"`
UpdatedAt time.Time `json:"updatedAt"`
}
type CreateRoleDTO struct {
Code string `json:"code" binding:"required"`
Name string `json:"name" binding:"required"`
GuardName string `json:"guardName" binding:"required"`
}
type UpdateRoleDTO struct {
Code string `json:"code" binding:"required"`
Name string `json:"name" binding:"required"`
GuardName string `json:"guardName" binding:"required"`
}
type ListFilter struct {
RoleName string
Page int
Limit int
}
type ListRoleDTO struct {
Count int64 `json:"count"`
Roles []RoleDTO `json:"roles"`
}

View File

@@ -0,0 +1,242 @@
package role
import (
"errors"
"net/http"
"strconv"
"strings"
"online-back/internal/appresult"
"online-back/internal/handlers"
"online-back/pkg/logging"
"github.com/gin-gonic/gin"
"github.com/jackc/pgx/v4"
)
const baseURL = "/roles"
type handler struct {
logger *logging.Logger
repository Repository
}
func NewHandler(logger *logging.Logger, repository Repository) handlers.Handler {
return &handler{logger: logger, repository: repository}
}
func (h *handler) Register(router *gin.RouterGroup) {
group := router.Group(baseURL, appresult.JwtTokenCheck())
group.GET("", h.list)
group.GET("/:id", h.getByID)
group.POST("", h.create)
group.PUT("/:id", h.update)
group.DELETE("/:id", h.delete)
}
// list godoc
// @Summary List roles
// @Description Returns paginated roles with optional filters
// @Tags role
// @Produce json
// @Security BearerAuth
// @Param role_name query string false "Filter by name"
// @Param page query int false "Page number" default(1)
// @Param limit query int false "Items per page" default(10)
// @Success 200 {object} appresult.AppSuccess
// @Failure 400 {object} appresult.AppError
// @Failure 500 {object} appresult.AppError
// @Router /roles [get]
func (h *handler) list(c *gin.Context) {
filter, ok := parseListFilter(c)
if !ok {
c.JSON(http.StatusBadRequest, appresult.ErrMissingParam)
return
}
result, err := h.repository.List(c.Request.Context(), filter)
if err != nil {
h.logger.Errorf("list roles failed: %v", err)
c.JSON(http.StatusInternalServerError, appresult.ErrInternalServer)
return
}
c.JSON(http.StatusOK, appresult.SuccessWithData(result))
}
// getByID godoc
// @Summary Get role by ID
// @Description Returns a single role
// @Tags role
// @Produce json
// @Security BearerAuth
// @Param id path int true "Role ID"
// @Success 200 {object} appresult.AppSuccess
// @Failure 400 {object} appresult.AppError
// @Failure 404 {object} appresult.AppError
// @Failure 500 {object} appresult.AppError
// @Router /roles/{id} [get]
func (h *handler) getByID(c *gin.Context) {
id, ok := parseID(c.Param("id"))
if !ok {
c.JSON(http.StatusBadRequest, appresult.ErrMissingParam)
return
}
item, err := h.repository.GetByID(c.Request.Context(), id)
if errors.Is(err, pgx.ErrNoRows) {
c.JSON(http.StatusNotFound, appresult.ErrNotFound)
return
}
if err != nil {
h.logger.Errorf("get role failed: %v", err)
c.JSON(http.StatusInternalServerError, appresult.ErrInternalServer)
return
}
c.JSON(http.StatusOK, appresult.SuccessWithData(item))
}
// create godoc
// @Summary Create role
// @Description Creates a new role
// @Tags role
// @Accept json
// @Produce json
// @Security BearerAuth
// @Param body body CreateRoleDTO true "Role payload"
// @Success 201 {object} appresult.AppSuccess
// @Failure 400 {object} appresult.AppError
// @Failure 500 {object} appresult.AppError
// @Router /roles [post]
func (h *handler) create(c *gin.Context) {
var dto CreateRoleDTO
if err := c.ShouldBindJSON(&dto); err != nil {
c.JSON(http.StatusBadRequest, appresult.ErrMissingParam)
return
}
item, err := h.repository.Create(c.Request.Context(), dto)
if err != nil {
h.logger.Errorf("create role failed: %v", err)
c.JSON(http.StatusInternalServerError, appresult.ErrInternalServer)
return
}
c.JSON(http.StatusCreated, appresult.SuccessWithData(item))
}
// update godoc
// @Summary Update role
// @Description Updates an existing role
// @Tags role
// @Accept json
// @Produce json
// @Security BearerAuth
// @Param id path int true "Role ID"
// @Param body body UpdateRoleDTO true "Role payload"
// @Success 200 {object} appresult.AppSuccess
// @Failure 400 {object} appresult.AppError
// @Failure 404 {object} appresult.AppError
// @Failure 500 {object} appresult.AppError
// @Router /roles/{id} [put]
func (h *handler) update(c *gin.Context) {
id, ok := parseID(c.Param("id"))
if !ok {
c.JSON(http.StatusBadRequest, appresult.ErrMissingParam)
return
}
var dto UpdateRoleDTO
if err := c.ShouldBindJSON(&dto); err != nil {
c.JSON(http.StatusBadRequest, appresult.ErrMissingParam)
return
}
item, err := h.repository.Update(c.Request.Context(), id, dto)
if errors.Is(err, pgx.ErrNoRows) {
c.JSON(http.StatusNotFound, appresult.ErrNotFound)
return
}
if err != nil {
h.logger.Errorf("update role failed: %v", err)
c.JSON(http.StatusInternalServerError, appresult.ErrInternalServer)
return
}
c.JSON(http.StatusOK, appresult.SuccessWithData(item))
}
// delete godoc
// @Summary Delete role
// @Description Deletes a role
// @Tags role
// @Produce json
// @Security BearerAuth
// @Param id path int true "Role ID"
// @Success 200 {object} appresult.AppSuccess
// @Failure 400 {object} appresult.AppError
// @Failure 404 {object} appresult.AppError
// @Failure 500 {object} appresult.AppError
// @Router /roles/{id} [delete]
func (h *handler) delete(c *gin.Context) {
id, ok := parseID(c.Param("id"))
if !ok {
c.JSON(http.StatusBadRequest, appresult.ErrMissingParam)
return
}
if err := h.repository.Delete(c.Request.Context(), id); errors.Is(err, pgx.ErrNoRows) {
c.JSON(http.StatusNotFound, appresult.ErrNotFound)
return
} else if err != nil {
h.logger.Errorf("delete role failed: %v", err)
c.JSON(http.StatusInternalServerError, appresult.ErrInternalServer)
return
}
c.JSON(http.StatusOK, appresult.SuccessWithData("role removed"))
}
func parseID(raw string) (int64, bool) {
id, err := strconv.ParseInt(raw, 10, 64)
if err != nil || id <= 0 {
return 0, false
}
return id, true
}
const (
defaultPage = 1
defaultLimit = 10
maxLimit = 100
)
func parseListFilter(c *gin.Context) (ListFilter, bool) {
filter := ListFilter{
Page: defaultPage,
Limit: defaultLimit,
}
if raw := c.Query("page"); raw != "" {
page, err := strconv.Atoi(raw)
if err != nil || page < 1 {
return ListFilter{}, false
}
filter.Page = page
}
if raw := c.Query("limit"); raw != "" {
limit, err := strconv.Atoi(raw)
if err != nil || limit < 1 || limit > maxLimit {
return ListFilter{}, false
}
filter.Limit = limit
}
if raw := strings.TrimSpace(c.Query("role_name")); raw != "" {
filter.RoleName = raw
}
return filter, true
}

View File

@@ -0,0 +1,11 @@
package role
import "context"
type Repository interface {
List(ctx context.Context, filter ListFilter) (ListRoleDTO, error)
GetByID(ctx context.Context, id int64) (RoleDTO, error)
Create(ctx context.Context, dto CreateRoleDTO) (RoleDTO, error)
Update(ctx context.Context, id int64, dto UpdateRoleDTO) (RoleDTO, error)
Delete(ctx context.Context, id int64) error
}