package asset import ( "context" "errors" "time" "github.com/google/uuid" "go.uber.org/fx" "gorm.io/gorm" domainAsset "base/internal/domain/asset" ) type categoryRepository struct { db *gorm.DB } func NewCategoryRepository(lc fx.Lifecycle, db *gorm.DB) domainAsset.CategoryRepository { lc.Append( fx.Hook{ OnStart: func(ctx context.Context) error { return nil }, OnStop: func(ctx context.Context) error { return nil }, }) return &categoryRepository{db: db} } func (r *categoryRepository) Create(ctx context.Context, category *domainAsset.Category) error { model := toCategoryModel(category) now := time.Now() model.CreatedAt = now model.UpdatedAt = now if err := r.db.WithContext(ctx).Create(model).Error; err != nil { return err } category.ID = model.ID return nil } func (r *categoryRepository) FindByID(ctx context.Context, id uuid.UUID) (*domainAsset.Category, error) { var model CategoryModel if err := r.db.WithContext(ctx).Where("id = ?", id).First(&model).Error; err != nil { if errors.Is(err, gorm.ErrRecordNotFound) { return nil, errors.New("category not found") } return nil, err } return toCategoryDomain(&model), nil } func (r *categoryRepository) Update(ctx context.Context, category *domainAsset.Category) error { model := toCategoryModel(category) model.UpdatedAt = time.Now() return r.db.WithContext(ctx).Model(&CategoryModel{}).Where("id = ?", category.ID).Updates(model).Error } func (r *categoryRepository) Delete(ctx context.Context, id uuid.UUID) error { return r.db.WithContext(ctx).Delete(&CategoryModel{}, "id = ?", id).Error } func (r *categoryRepository) FindAll(ctx context.Context) ([]*domainAsset.Category, error) { var models []CategoryModel if err := r.db.WithContext(ctx).Order("name ASC").Find(&models).Error; err != nil { return nil, err } out := make([]*domainAsset.Category, len(models)) for i := range models { out[i] = toCategoryDomain(&models[i]) } return out, nil } func (r *categoryRepository) FindByIDs(ctx context.Context, ids []uuid.UUID) ([]*domainAsset.Category, error) { if len(ids) == 0 { return nil, nil } var models []CategoryModel if err := r.db.WithContext(ctx).Where("id IN ?", ids).Order("name ASC").Find(&models).Error; err != nil { return nil, err } out := make([]*domainAsset.Category, len(models)) for i := range models { out[i] = toCategoryDomain(&models[i]) } return out, nil }