S SmartDocs
Series: Go go 46 lines · Updated 2026-04-18

payment_repo.go

Go/payment-gateway-challenge/internal/repository/payment_repo.go

// Package repository persists Payment aggregates. The interface keeps HTTP
// handlers testable with in-memory fakes.
package repository

import (
	"context"
	"fmt"

	"payment-gateway-challenge/internal/models"

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

// PaymentWriterReader abstracts storage for tests.
type PaymentWriterReader interface {
	Create(ctx context.Context, p *models.Payment) error
	GetByID(ctx context.Context, id uuid.UUID) (*models.Payment, error)
}

// GormPaymentRepo is the PostgreSQL-backed implementation.
type GormPaymentRepo struct {
	db *gorm.DB
}

// NewGormPaymentRepo constructs a repository.
func NewGormPaymentRepo(db *gorm.DB) *GormPaymentRepo {
	return &GormPaymentRepo{db: db}
}

// Create inserts a new payment row. Caller must pre-fill ID and all fields.
func (r *GormPaymentRepo) Create(ctx context.Context, p *models.Payment) error {
	if err := r.db.WithContext(ctx).Create(p).Error; err != nil {
		return fmt.Errorf("insert payment: %w", err)
	}
	return nil
}

// GetByID loads a payment by primary key.
func (r *GormPaymentRepo) GetByID(ctx context.Context, id uuid.UUID) (*models.Payment, error) {
	var p models.Payment
	if err := r.db.WithContext(ctx).First(&p, id).Error; err != nil {
		return nil, err
	}
	return &p, nil
}

Related articles