changed arhitecture
This commit is contained in:
151
internal/org/province/db/postgresql.go
Normal file
151
internal/org/province/db/postgresql.go
Normal file
@@ -0,0 +1,151 @@
|
||||
package db
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"strings"
|
||||
|
||||
"online-back/internal/org/province"
|
||||
"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[province.ProvinceDTO]
|
||||
logger *logging.Logger
|
||||
}
|
||||
|
||||
func NewRepository(client postgresql.Client, logger *logging.Logger) province.Repository {
|
||||
return &repository{
|
||||
client: client,
|
||||
generic: genericrepo.New(client, "provinces", provinceSelectColumns, scanProvince),
|
||||
logger: logger,
|
||||
}
|
||||
}
|
||||
|
||||
const provinceSelectColumns = `id, name, region, active`
|
||||
|
||||
func (r *repository) List(ctx context.Context, filter province.ListFilter) (province.ListProvinceDTO, error) {
|
||||
whereClause, args := buildListQuery(filter)
|
||||
|
||||
items, count, err := r.generic.List(ctx, whereClause, args, filter.Page, filter.Limit, "id")
|
||||
if err != nil {
|
||||
return province.ListProvinceDTO{}, err
|
||||
}
|
||||
|
||||
return province.ListProvinceDTO{Count: count, Provinces: items}, nil
|
||||
}
|
||||
|
||||
func buildListQuery(filter province.ListFilter) (whereClause string, args []interface{}) {
|
||||
var conditions []string
|
||||
|
||||
if filter.Name != "" {
|
||||
args = append(args, likePattern(filter.Name))
|
||||
n := len(args)
|
||||
conditions = append(conditions, fmt.Sprintf(`(
|
||||
name->>'en' ILIKE $%[1]d OR name->>'ru' ILIKE $%[1]d OR name->>'tm' ILIKE $%[1]d
|
||||
)`, n))
|
||||
}
|
||||
|
||||
if filter.Region != "" {
|
||||
args = append(args, likePattern(filter.Region))
|
||||
n := len(args)
|
||||
conditions = append(conditions, fmt.Sprintf(`(
|
||||
region->>'en' ILIKE $%[1]d OR region->>'ru' ILIKE $%[1]d OR region->>'tm' ILIKE $%[1]d
|
||||
)`, n))
|
||||
}
|
||||
|
||||
if filter.Active != nil {
|
||||
args = append(args, *filter.Active)
|
||||
conditions = append(conditions, fmt.Sprintf("active = $%d", len(args)))
|
||||
}
|
||||
|
||||
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) (province.ProvinceDTO, error) {
|
||||
return r.generic.GetByID(ctx, id)
|
||||
}
|
||||
|
||||
func (r *repository) Create(ctx context.Context, dto province.CreateProvinceDTO) (province.ProvinceDTO, error) {
|
||||
name, region, err := marshalProvinceJSON(dto.Name, dto.Region)
|
||||
if err != nil {
|
||||
return province.ProvinceDTO{}, err
|
||||
}
|
||||
|
||||
active := true
|
||||
if dto.Active != nil {
|
||||
active = *dto.Active
|
||||
}
|
||||
|
||||
row := r.client.QueryRow(ctx,
|
||||
`INSERT INTO provinces (name, region, active) VALUES ($1, $2, $3) RETURNING `+provinceSelectColumns,
|
||||
name, region, active,
|
||||
)
|
||||
return scanProvince(row)
|
||||
}
|
||||
|
||||
func (r *repository) Update(ctx context.Context, id int64, dto province.UpdateProvinceDTO) (province.ProvinceDTO, error) {
|
||||
name, region, err := marshalProvinceJSON(dto.Name, dto.Region)
|
||||
if err != nil {
|
||||
return province.ProvinceDTO{}, err
|
||||
}
|
||||
|
||||
row := r.client.QueryRow(ctx,
|
||||
`UPDATE provinces SET name = $1, region = $2, active = $3 WHERE id = $4 RETURNING `+provinceSelectColumns,
|
||||
name, region, dto.Active, id,
|
||||
)
|
||||
item, err := scanProvince(row)
|
||||
if errors.Is(err, pgx.ErrNoRows) {
|
||||
return province.ProvinceDTO{}, err
|
||||
}
|
||||
return item, err
|
||||
}
|
||||
|
||||
func (r *repository) Delete(ctx context.Context, id int64) error {
|
||||
return r.generic.Delete(ctx, id)
|
||||
}
|
||||
|
||||
func marshalProvinceJSON(name, region province.LocalizedName) ([]byte, []byte, error) {
|
||||
nameJSON, err := json.Marshal(name)
|
||||
if err != nil {
|
||||
return nil, nil, err
|
||||
}
|
||||
regionJSON, err := json.Marshal(region)
|
||||
if err != nil {
|
||||
return nil, nil, err
|
||||
}
|
||||
return nameJSON, regionJSON, nil
|
||||
}
|
||||
|
||||
func scanProvince(row genericrepo.Scanner) (province.ProvinceDTO, error) {
|
||||
var item province.ProvinceDTO
|
||||
var nameJSON, regionJSON []byte
|
||||
if err := row.Scan(&item.Id, &nameJSON, ®ionJSON, &item.Active); err != nil {
|
||||
return province.ProvinceDTO{}, err
|
||||
}
|
||||
if err := json.Unmarshal(nameJSON, &item.Name); err != nil {
|
||||
return province.ProvinceDTO{}, err
|
||||
}
|
||||
if err := json.Unmarshal(regionJSON, &item.Region); err != nil {
|
||||
return province.ProvinceDTO{}, err
|
||||
}
|
||||
return item, nil
|
||||
}
|
||||
39
internal/org/province/dto.go
Normal file
39
internal/org/province/dto.go
Normal file
@@ -0,0 +1,39 @@
|
||||
package province
|
||||
|
||||
type LocalizedName struct {
|
||||
En string `json:"en"`
|
||||
Ru string `json:"ru"`
|
||||
Tm string `json:"tm"`
|
||||
}
|
||||
|
||||
type ProvinceDTO struct {
|
||||
Id int64 `json:"id"`
|
||||
Name LocalizedName `json:"name"`
|
||||
Region LocalizedName `json:"region"`
|
||||
Active bool `json:"active"`
|
||||
}
|
||||
|
||||
type CreateProvinceDTO struct {
|
||||
Name LocalizedName `json:"name" binding:"required"`
|
||||
Region LocalizedName `json:"region" binding:"required"`
|
||||
Active *bool `json:"active"`
|
||||
}
|
||||
|
||||
type UpdateProvinceDTO struct {
|
||||
Name LocalizedName `json:"name" binding:"required"`
|
||||
Region LocalizedName `json:"region" binding:"required"`
|
||||
Active bool `json:"active"`
|
||||
}
|
||||
|
||||
type ListFilter struct {
|
||||
Name string
|
||||
Region string
|
||||
Active *bool
|
||||
Page int
|
||||
Limit int
|
||||
}
|
||||
|
||||
type ListProvinceDTO struct {
|
||||
Count int64 `json:"count"`
|
||||
Provinces []ProvinceDTO `json:"provinces"`
|
||||
}
|
||||
256
internal/org/province/handler.go
Normal file
256
internal/org/province/handler.go
Normal file
@@ -0,0 +1,256 @@
|
||||
package province
|
||||
|
||||
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 = "/provinces"
|
||||
|
||||
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 provinces
|
||||
// @Description Returns paginated provinces with optional filters
|
||||
// @Tags province
|
||||
// @Produce json
|
||||
// @Security BearerAuth
|
||||
// @Param name query string false "Filter by province name (en, ru, tm)"
|
||||
// @Param region query string false "Filter by region (en, ru, tm)"
|
||||
// @Param active query bool false "Filter by active status"
|
||||
// @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 /provinces [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 provinces failed: %v", err)
|
||||
c.JSON(http.StatusInternalServerError, appresult.ErrInternalServer)
|
||||
return
|
||||
}
|
||||
|
||||
c.JSON(http.StatusOK, appresult.SuccessWithData(result))
|
||||
}
|
||||
|
||||
// getByID godoc
|
||||
// @Summary Get province by ID
|
||||
// @Description Returns a single province
|
||||
// @Tags province
|
||||
// @Produce json
|
||||
// @Security BearerAuth
|
||||
// @Param id path int true "Province ID"
|
||||
// @Success 200 {object} appresult.AppSuccess
|
||||
// @Failure 400 {object} appresult.AppError
|
||||
// @Failure 404 {object} appresult.AppError
|
||||
// @Failure 500 {object} appresult.AppError
|
||||
// @Router /provinces/{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 province failed: %v", err)
|
||||
c.JSON(http.StatusInternalServerError, appresult.ErrInternalServer)
|
||||
return
|
||||
}
|
||||
|
||||
c.JSON(http.StatusOK, appresult.SuccessWithData(item))
|
||||
}
|
||||
|
||||
// create godoc
|
||||
// @Summary Create province
|
||||
// @Description Creates a new province
|
||||
// @Tags province
|
||||
// @Accept json
|
||||
// @Produce json
|
||||
// @Security BearerAuth
|
||||
// @Param body body CreateProvinceDTO true "Province payload"
|
||||
// @Success 201 {object} appresult.AppSuccess
|
||||
// @Failure 400 {object} appresult.AppError
|
||||
// @Failure 500 {object} appresult.AppError
|
||||
// @Router /provinces [post]
|
||||
func (h *handler) create(c *gin.Context) {
|
||||
var dto CreateProvinceDTO
|
||||
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 province failed: %v", err)
|
||||
c.JSON(http.StatusInternalServerError, appresult.ErrInternalServer)
|
||||
return
|
||||
}
|
||||
|
||||
c.JSON(http.StatusCreated, appresult.SuccessWithData(item))
|
||||
}
|
||||
|
||||
// update godoc
|
||||
// @Summary Update province
|
||||
// @Description Updates an existing province
|
||||
// @Tags province
|
||||
// @Accept json
|
||||
// @Produce json
|
||||
// @Security BearerAuth
|
||||
// @Param id path int true "Province ID"
|
||||
// @Param body body UpdateProvinceDTO true "Province payload"
|
||||
// @Success 200 {object} appresult.AppSuccess
|
||||
// @Failure 400 {object} appresult.AppError
|
||||
// @Failure 404 {object} appresult.AppError
|
||||
// @Failure 500 {object} appresult.AppError
|
||||
// @Router /provinces/{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 UpdateProvinceDTO
|
||||
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 province failed: %v", err)
|
||||
c.JSON(http.StatusInternalServerError, appresult.ErrInternalServer)
|
||||
return
|
||||
}
|
||||
|
||||
c.JSON(http.StatusOK, appresult.SuccessWithData(item))
|
||||
}
|
||||
|
||||
// delete godoc
|
||||
// @Summary Delete province
|
||||
// @Description Deletes a province
|
||||
// @Tags province
|
||||
// @Produce json
|
||||
// @Security BearerAuth
|
||||
// @Param id path int true "Province ID"
|
||||
// @Success 200 {object} appresult.AppSuccess
|
||||
// @Failure 400 {object} appresult.AppError
|
||||
// @Failure 404 {object} appresult.AppError
|
||||
// @Failure 500 {object} appresult.AppError
|
||||
// @Router /provinces/{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 province failed: %v", err)
|
||||
c.JSON(http.StatusInternalServerError, appresult.ErrInternalServer)
|
||||
return
|
||||
}
|
||||
|
||||
c.JSON(http.StatusOK, appresult.SuccessWithData("province 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("name")); raw != "" {
|
||||
filter.Name = raw
|
||||
}
|
||||
|
||||
if raw := strings.TrimSpace(c.Query("region")); raw != "" {
|
||||
filter.Region = raw
|
||||
}
|
||||
|
||||
if raw := c.Query("active"); raw != "" {
|
||||
active, err := strconv.ParseBool(raw)
|
||||
if err != nil {
|
||||
return ListFilter{}, false
|
||||
}
|
||||
filter.Active = &active
|
||||
}
|
||||
|
||||
return filter, true
|
||||
}
|
||||
11
internal/org/province/storage.go
Normal file
11
internal/org/province/storage.go
Normal file
@@ -0,0 +1,11 @@
|
||||
package province
|
||||
|
||||
import "context"
|
||||
|
||||
type Repository interface {
|
||||
List(ctx context.Context, filter ListFilter) (ListProvinceDTO, error)
|
||||
GetByID(ctx context.Context, id int64) (ProvinceDTO, error)
|
||||
Create(ctx context.Context, dto CreateProvinceDTO) (ProvinceDTO, error)
|
||||
Update(ctx context.Context, id int64, dto UpdateProvinceDTO) (ProvinceDTO, error)
|
||||
Delete(ctx context.Context, id int64) error
|
||||
}
|
||||
Reference in New Issue
Block a user