refactor(backend/db): remove ctx argument from transaction wrapper
This commit is contained in:
parent
5ac528be05
commit
59eacd6bc5
@ -1,49 +1,50 @@
|
|||||||
package db
|
package db
|
||||||
|
|
||||||
import (
|
import (
|
||||||
"context"
|
"context"
|
||||||
"fmt"
|
"fmt"
|
||||||
"net/http"
|
"net/http"
|
||||||
"time"
|
"time"
|
||||||
|
|
||||||
"github.com/jackc/pgx/v5"
|
"github.com/jackc/pgx/v5"
|
||||||
"github.com/jackc/pgx/v5/pgxpool"
|
"github.com/jackc/pgx/v5/pgxpool"
|
||||||
)
|
)
|
||||||
|
|
||||||
var connPool *pgxpool.Pool
|
var connPool *pgxpool.Pool
|
||||||
|
|
||||||
func InitDB(connString string) error {
|
func InitDB(connString string) error {
|
||||||
poolConfig, err := pgxpool.ParseConfig(connString)
|
poolConfig, err := pgxpool.ParseConfig(connString)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return fmt.Errorf("error while parsing connection string: %w", err)
|
return fmt.Errorf("error while parsing connection string: %w", err)
|
||||||
}
|
}
|
||||||
|
|
||||||
poolConfig.MaxConns = 100
|
poolConfig.MaxConns = 100
|
||||||
poolConfig.MinConns = 0
|
poolConfig.MinConns = 0
|
||||||
poolConfig.MaxConnLifetime = time.Hour
|
poolConfig.MaxConnLifetime = time.Hour
|
||||||
poolConfig.HealthCheckPeriod = 30 * time.Second
|
poolConfig.HealthCheckPeriod = 30 * time.Second
|
||||||
|
|
||||||
connPool, err = pgxpool.NewWithConfig(context.Background(), poolConfig)
|
connPool, err = pgxpool.NewWithConfig(context.Background(), poolConfig)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return fmt.Errorf("error while initializing DB connections pool: %w", err)
|
return fmt.Errorf("error while initializing DB connections pool: %w", err)
|
||||||
}
|
}
|
||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
|
|
||||||
func transaction(ctx context.Context, handler func(pgx.Tx) (statusCode int, err error)) (statusCode int, err error) {
|
func transaction(handler func(context.Context, pgx.Tx) (statusCode int, err error)) (statusCode int, err error) {
|
||||||
tx, err := connPool.Begin(ctx)
|
ctx := context.Background()
|
||||||
if err != nil {
|
tx, err := connPool.Begin(ctx)
|
||||||
statusCode = http.StatusInternalServerError
|
if err != nil {
|
||||||
return
|
statusCode = http.StatusInternalServerError
|
||||||
}
|
return
|
||||||
statusCode, err = handler(tx)
|
}
|
||||||
if err != nil {
|
statusCode, err = handler(ctx, tx)
|
||||||
tx.Rollback(ctx)
|
if err != nil {
|
||||||
return
|
tx.Rollback(ctx)
|
||||||
}
|
return
|
||||||
err = tx.Commit(ctx)
|
}
|
||||||
if err != nil {
|
err = tx.Commit(ctx)
|
||||||
statusCode = http.StatusInternalServerError
|
if err != nil {
|
||||||
}
|
statusCode = http.StatusInternalServerError
|
||||||
return
|
}
|
||||||
}
|
return
|
||||||
|
}
|
||||||
|
|||||||
Loading…
x
Reference in New Issue
Block a user