refactor(backend): switch to DDD
This commit is contained in:
@@ -0,0 +1,50 @@
|
||||
package postgres
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"time"
|
||||
|
||||
"github.com/jackc/pgx/v5"
|
||||
"github.com/jackc/pgx/v5/pgxpool"
|
||||
|
||||
"tanabata/internal/domain"
|
||||
)
|
||||
|
||||
// Initialize PostgreSQL database driver
|
||||
func New(dbURL string) (*pgxpool.Pool, error) {
|
||||
poolConfig, err := pgxpool.ParseConfig(dbURL)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("error while parsing connection string: %w", err)
|
||||
}
|
||||
|
||||
poolConfig.MaxConns = 100
|
||||
poolConfig.MinConns = 0
|
||||
poolConfig.MaxConnLifetime = time.Hour
|
||||
poolConfig.HealthCheckPeriod = 30 * time.Second
|
||||
|
||||
db, err := pgxpool.NewWithConfig(context.Background(), poolConfig)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("error while initializing DB connections pool: %w", err)
|
||||
}
|
||||
return db, nil
|
||||
}
|
||||
|
||||
// Transaction wrapper
|
||||
func transaction(ctx context.Context, db *pgxpool.Pool, handler func(context.Context, pgx.Tx) *domain.DomainError) (domainErr *domain.DomainError) {
|
||||
tx, err := db.Begin(ctx)
|
||||
if err != nil {
|
||||
domainErr = domain.NewUnexpectedError(err)
|
||||
return
|
||||
}
|
||||
domainErr = handler(ctx, tx)
|
||||
if domainErr != nil {
|
||||
tx.Rollback(ctx)
|
||||
return
|
||||
}
|
||||
err = tx.Commit(ctx)
|
||||
if err != nil {
|
||||
domainErr = domain.NewUnexpectedError(err)
|
||||
}
|
||||
return
|
||||
}
|
||||
Reference in New Issue
Block a user