refactor: migrate from raw pgx to GORM, unify ErrNoRows, cleanup auth
ci / build (push) Successful in 2m58s
ci / build (pull_request) Successful in 2m47s

This commit is contained in:
Mephimeow
2026-06-14 16:41:33 +00:00
parent 9da532e9dc
commit 2da484d781
19 changed files with 321 additions and 348 deletions
+8 -2
View File
@@ -4,6 +4,7 @@ import (
"errors"
"log"
"net/http"
"strconv"
"github.com/gin-gonic/gin"
)
@@ -76,16 +77,21 @@ func (h *Handler) GetByID(c *gin.Context) {
}
// @Summary List organizations
// @Description Get all organizations
// @Description Get all organizations with pagination
// @Tags organizations
// @Accept json
// @Produce json
// @Security Bearer
// @Param limit query int false "Page size (default 20)"
// @Param offset query int false "Offset (default 0)"
// @Success 200 {object} OrgListResponse
// @Failure 500 {object} ErrorResponse
// @Router /api/organizations [get]
func (h *Handler) List(c *gin.Context) {
resp, err := h.service.List(c.Request.Context())
limit, _ := strconv.Atoi(c.DefaultQuery("limit", "20"))
offset, _ := strconv.Atoi(c.DefaultQuery("offset", "0"))
resp, err := h.service.List(c.Request.Context(), limit, offset)
if err != nil {
log.Printf("list orgs error: %v", err)
c.JSON(http.StatusInternalServerError, ErrorResponse{Error: "internal server error"})
+8 -6
View File
@@ -3,16 +3,16 @@ package org
import "time"
type Organization struct {
ID string `json:"id"`
Name string `json:"name"`
Slug string `json:"slug"`
CreatedAt time.Time `json:"created_at"`
UpdatedAt time.Time `json:"updated_at"`
ID string `gorm:"type:uuid;primaryKey" json:"id"`
Name string `gorm:"type:text;not null" json:"name"`
Slug string `gorm:"type:text;not null;uniqueIndex" json:"slug"`
CreatedAt time.Time `gorm:"autoCreateTime" json:"created_at"`
UpdatedAt time.Time `gorm:"autoUpdateTime" json:"updated_at"`
}
type CreateOrgRequest struct {
Name string `json:"name" binding:"required,min=2,max=100" example:"My Corp"`
Slug string `json:"slug" binding:"required,min=2,max=50" example:"my-corp"`
Slug string `json:"slug" binding:"required,min=2,max=50" example:"my-corp"`
}
type UpdateOrgRequest struct {
@@ -26,6 +26,8 @@ type OrgResponse struct {
type OrgListResponse struct {
Organizations []Organization `json:"organizations"`
Total int `json:"total"`
Limit int `json:"limit"`
Offset int `json:"offset"`
}
type ErrorResponse struct {
+36 -42
View File
@@ -5,18 +5,24 @@ import (
"time"
"github.com/google/uuid"
"github.com/jackc/pgx/v5"
"github.com/jackc/pgx/v5/pgxpool"
"gorm.io/gorm"
)
var ErrNoRows = pgx.ErrNoRows
type Repository struct {
pool *pgxpool.Pool
type OrgRepository interface {
Create(ctx context.Context, org *Organization) error
FindByID(ctx context.Context, id string) (*Organization, error)
FindAll(ctx context.Context, limit, offset int) ([]Organization, error)
Count(ctx context.Context) (int, error)
Update(ctx context.Context, org *Organization) error
Delete(ctx context.Context, id string) (bool, error)
}
func NewRepository(pool *pgxpool.Pool) *Repository {
return &Repository{pool: pool}
type Repository struct {
db *gorm.DB
}
func NewRepository(db *gorm.DB) *Repository {
return &Repository{db: db}
}
func (r *Repository) Create(ctx context.Context, org *Organization) error {
@@ -24,54 +30,42 @@ func (r *Repository) Create(ctx context.Context, org *Organization) error {
now := time.Now().UTC()
org.CreatedAt = now
org.UpdatedAt = now
_, err := r.pool.Exec(ctx,
`INSERT INTO organizations (id, name, slug, created_at, updated_at) VALUES ($1, $2, $3, $4, $5)`,
org.ID, org.Name, org.Slug, org.CreatedAt, org.UpdatedAt,
)
return err
return r.db.WithContext(ctx).Create(org).Error
}
func (r *Repository) FindByID(ctx context.Context, id string) (*Organization, error) {
var org Organization
err := r.pool.QueryRow(ctx,
`SELECT id, name, slug, created_at, updated_at FROM organizations WHERE id = $1`, id,
).Scan(&org.ID, &org.Name, &org.Slug, &org.CreatedAt, &org.UpdatedAt)
err := r.db.WithContext(ctx).Where("id = ?", id).First(&org).Error
if err != nil {
return nil, err
}
return &org, nil
}
func (r *Repository) FindAll(ctx context.Context) ([]Organization, error) {
rows, err := r.pool.Query(ctx,
`SELECT id, name, slug, created_at, updated_at FROM organizations ORDER BY created_at DESC`,
)
if err != nil {
return nil, err
}
defer rows.Close()
func (r *Repository) FindAll(ctx context.Context, limit, offset int) ([]Organization, error) {
var orgs []Organization
for rows.Next() {
var org Organization
if err := rows.Scan(&org.ID, &org.Name, &org.Slug, &org.CreatedAt, &org.UpdatedAt); err != nil {
return nil, err
}
orgs = append(orgs, org)
}
return orgs, rows.Err()
err := r.db.WithContext(ctx).
Order("created_at DESC").
Limit(limit).
Offset(offset).
Find(&orgs).Error
return orgs, err
}
func (r *Repository) Count(ctx context.Context) (int, error) {
var total int64
err := r.db.WithContext(ctx).Model(&Organization{}).Count(&total).Error
return int(total), err
}
func (r *Repository) Update(ctx context.Context, org *Organization) error {
org.UpdatedAt = time.Now().UTC()
_, err := r.pool.Exec(ctx,
`UPDATE organizations SET name = $1, updated_at = $2 WHERE id = $3`,
org.Name, org.UpdatedAt, org.ID,
)
return err
return r.db.WithContext(ctx).Model(org).Update("name", org.Name).Error
}
func (r *Repository) Delete(ctx context.Context, id string) error {
_, err := r.pool.Exec(ctx, `DELETE FROM organizations WHERE id = $1`, id)
return err
func (r *Repository) Delete(ctx context.Context, id string) (bool, error) {
result := r.db.WithContext(ctx).Delete(&Organization{}, "id = ?", id)
if result.Error != nil {
return false, result.Error
}
return result.RowsAffected > 0, nil
}
+34 -18
View File
@@ -5,6 +5,8 @@ import (
"errors"
"fmt"
"strings"
"gitea.d3m0k1d.ru/HellreigN/Control-plane/internal/db"
)
var (
@@ -13,10 +15,10 @@ var (
)
type Service struct {
repo *Repository
repo OrgRepository
}
func NewService(repo *Repository) *Service {
func NewService(repo OrgRepository) *Service {
return &Service{repo: repo}
}
@@ -41,7 +43,7 @@ func (s *Service) Create(ctx context.Context, req CreateOrgRequest) (*Organizati
func (s *Service) GetByID(ctx context.Context, id string) (*Organization, error) {
org, err := s.repo.FindByID(ctx, id)
if err != nil {
if errors.Is(err, ErrNoRows) {
if errors.Is(err, db.ErrNoRows) {
return nil, ErrNotFound
}
return nil, fmt.Errorf("failed to find organization: %w", err)
@@ -49,8 +51,20 @@ func (s *Service) GetByID(ctx context.Context, id string) (*Organization, error)
return org, nil
}
func (s *Service) List(ctx context.Context) (*OrgListResponse, error) {
orgs, err := s.repo.FindAll(ctx)
func (s *Service) List(ctx context.Context, limit, offset int) (*OrgListResponse, error) {
if limit <= 0 {
limit = 20
}
if offset < 0 {
offset = 0
}
total, err := s.repo.Count(ctx)
if err != nil {
return nil, fmt.Errorf("failed to count organizations: %w", err)
}
orgs, err := s.repo.FindAll(ctx, limit, offset)
if err != nil {
return nil, fmt.Errorf("failed to list organizations: %w", err)
}
@@ -59,14 +73,20 @@ func (s *Service) List(ctx context.Context) (*OrgListResponse, error) {
}
return &OrgListResponse{
Organizations: orgs,
Total: len(orgs),
Total: total,
Limit: limit,
Offset: offset,
}, nil
}
func (s *Service) Update(ctx context.Context, id string, req UpdateOrgRequest) (*Organization, error) {
func (s *Service) Update(
ctx context.Context,
id string,
req UpdateOrgRequest,
) (*Organization, error) {
org, err := s.repo.FindByID(ctx, id)
if err != nil {
if errors.Is(err, ErrNoRows) {
if errors.Is(err, db.ErrNoRows) {
return nil, ErrNotFound
}
return nil, fmt.Errorf("failed to find organization: %w", err)
@@ -82,21 +102,17 @@ func (s *Service) Update(ctx context.Context, id string, req UpdateOrgRequest) (
}
func (s *Service) Delete(ctx context.Context, id string) error {
org, err := s.repo.FindByID(ctx, id)
found, err := s.repo.Delete(ctx, id)
if err != nil {
if errors.Is(err, ErrNoRows) {
return ErrNotFound
}
return fmt.Errorf("failed to find organization: %w", err)
}
if err := s.repo.Delete(ctx, org.ID); err != nil {
return fmt.Errorf("failed to delete organization: %w", err)
}
if !found {
return ErrNotFound
}
return nil
}
func isUniqueViolation(err error) bool {
return err != nil && (strings.Contains(err.Error(), "unique") || strings.Contains(err.Error(), "23505"))
return err != nil &&
(strings.Contains(err.Error(), "unique") || strings.Contains(err.Error(), "23505"))
}