feat(backend/db): add transaction wrapper
This commit is contained in:
+22
-2
@@ -3,12 +3,14 @@ package db
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"net/http"
|
||||
"time"
|
||||
|
||||
"github.com/jackc/pgx/v5"
|
||||
"github.com/jackc/pgx/v5/pgxpool"
|
||||
)
|
||||
|
||||
var ConnPool *pgxpool.Pool
|
||||
var connPool *pgxpool.Pool
|
||||
|
||||
func InitDB(connString string) error {
|
||||
poolConfig, err := pgxpool.ParseConfig(connString)
|
||||
@@ -21,9 +23,27 @@ func InitDB(connString string) error {
|
||||
poolConfig.MaxConnLifetime = time.Hour
|
||||
poolConfig.HealthCheckPeriod = 30 * time.Second
|
||||
|
||||
ConnPool, err = pgxpool.NewWithConfig(context.Background(), poolConfig)
|
||||
connPool, err = pgxpool.NewWithConfig(context.Background(), poolConfig)
|
||||
if err != nil {
|
||||
return fmt.Errorf("error while initializing DB connections pool: %w", err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func transaction(ctx context.Context, handler func(pgx.Tx) (statusCode int, err error)) (statusCode int, err error) {
|
||||
tx, err := connPool.Begin(ctx)
|
||||
if err != nil {
|
||||
statusCode = http.StatusInternalServerError
|
||||
return
|
||||
}
|
||||
statusCode, err = handler(tx)
|
||||
if err != nil {
|
||||
tx.Rollback(ctx)
|
||||
return
|
||||
}
|
||||
err = tx.Commit(ctx)
|
||||
if err != nil {
|
||||
statusCode = http.StatusInternalServerError
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user