S SmartDocs
시리즈: Go go 81 줄 · 업데이트 2026-04-18

goods_repo.go

Go/Baasid/internal/repository/goods_repo.go

package repository

import (
	"fmt"

	"baasid/internal/models"

	"github.com/google/uuid"
	"gorm.io/gorm"
)

// GoodsRepository performs CRUD on goods rows.
type GoodsRepository struct {
	db *gorm.DB
}

// NewGoodsRepository constructs a repository bound to gorm.DB.
func NewGoodsRepository(db *gorm.DB) *GoodsRepository {
	return &GoodsRepository{db: db}
}

// Create inserts a new product row. cr_user and up_user are both set to the
// authenticated operator at creation time per the data dictionary.
func (r *GoodsRepository) Create(operatorID uuid.UUID, name string) (*models.Goods, error) {
	g := &models.Goods{
		Name:   name,
		CrUser: operatorID,
		UpUser: operatorID,
	}
	if err := r.db.Create(g).Error; err != nil {
		return nil, fmt.Errorf("create goods: %w", err)
	}
	return g, nil
}

// ListAll returns every product ordered by creation time ascending.
func (r *GoodsRepository) ListAll() ([]models.Goods, error) {
	var list []models.Goods
	if err := r.db.Order("cr_datetime ASC").Find(&list).Error; err != nil {
		return nil, fmt.Errorf("list goods: %w", err)
	}
	return list, nil
}

// FindByID returns one product by primary key.
//
// GORM's First(&model, primaryKey) form generates SQL against the declared
// primary-key column ("_id" in our schema) without hard-coding column names.
func (r *GoodsRepository) FindByID(id uuid.UUID) (*models.Goods, error) {
	var g models.Goods
	if err := r.db.First(&g, id).Error; err != nil {
		return nil, fmt.Errorf("find goods: %w", err)
	}
	return &g, nil
}

// UpdateName changes the product title and refreshes up_user / up_datetime.
func (r *GoodsRepository) UpdateName(id, operatorID uuid.UUID, newName string) (*models.Goods, error) {
	var g models.Goods
	if err := r.db.First(&g, id).Error; err != nil {
		return nil, fmt.Errorf("find goods for update: %w", err)
	}
	g.Name = newName
	g.UpUser = operatorID
	if err := r.db.Save(&g).Error; err != nil {
		return nil, fmt.Errorf("save goods: %w", err)
	}
	return &g, nil
}

// DeleteByID removes a row by primary key.
func (r *GoodsRepository) DeleteByID(id uuid.UUID) error {
	res := r.db.Delete(&models.Goods{}, id)
	if res.Error != nil {
		return fmt.Errorf("delete goods: %w", res.Error)
	}
	if res.RowsAffected == 0 {
		return gorm.ErrRecordNotFound
	}
	return nil
}

관련 글