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