Skip to content

Commit

Permalink
refactor: ♻️ some refactoring in dbcontext
Browse files Browse the repository at this point in the history
  • Loading branch information
mehdihadeli committed Dec 18, 2023
1 parent e6a5a51 commit 6c00afc
Show file tree
Hide file tree
Showing 38 changed files with 1,107 additions and 443 deletions.
4 changes: 2 additions & 2 deletions internal/pkg/logger/external/gromlog/gorm.go
Original file line number Diff line number Diff line change
Expand Up @@ -21,11 +21,11 @@ func NewGormCustomLogger(logger logger.Logger) *GormCustomLogger {
//cfg, err := config.ProvideLogConfig()
//
//var logger logger.logger
//if cfg.LogType == models.Logrus && err != nil {
//if cfg.LogType == datamodels.Logrus && err != nil {
// logger = logrous.NewLogrusLogger(cfg, constants.Dev)
//} else {
// if err != nil {
// cfg = &config.LogOptions{LogLevel: "info", LogType: models.Zap}
// cfg = &config.LogOptions{LogLevel: "info", LogType: datamodels.Zap}
// }
// logger = zap.NewZapLogger(cfg, constants.Dev)
//}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ import (
"github.com/mehdihadeli/go-ecommerce-microservices/internal/pkg/otel/constants/telemetrytags"
"github.com/mehdihadeli/go-ecommerce-microservices/internal/pkg/otel/metrics"
customAttribute "github.com/mehdihadeli/go-ecommerce-microservices/internal/pkg/otel/tracing/attribute"
typemapper "github.com/mehdihadeli/go-ecommerce-microservices/internal/pkg/reflection/typemapper"
"github.com/mehdihadeli/go-ecommerce-microservices/internal/pkg/reflection/typemapper"

"github.com/mehdihadeli/go-mediatr"
"go.opentelemetry.io/otel/attribute"
Expand Down
3 changes: 2 additions & 1 deletion internal/pkg/otel/tracing/utils/utils.go
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ import (
"github.com/mehdihadeli/go-ecommerce-microservices/internal/pkg/core/metadata"
"github.com/mehdihadeli/go-ecommerce-microservices/internal/pkg/grpc/grpcerrors"
customErrors "github.com/mehdihadeli/go-ecommerce-microservices/internal/pkg/http/httperrors/customerrors"
problemdetails "github.com/mehdihadeli/go-ecommerce-microservices/internal/pkg/http/httperrors/problemdetails"
"github.com/mehdihadeli/go-ecommerce-microservices/internal/pkg/otel/constants/telemetrytags"
errorUtils "github.com/mehdihadeli/go-ecommerce-microservices/internal/pkg/utils/errorutils"

Expand All @@ -29,7 +30,7 @@ func HttpTraceStatusFromSpan(span trace.Span, err error) error {
isError := err != nil

if customErrors.IsCustomError(err) {
httpError := problemDetails.ParseError(err)
httpError := problemdetails.ParseError(err)

return HttpTraceStatusFromSpanWithCode(
span,
Expand Down
16 changes: 16 additions & 0 deletions internal/pkg/postgresgorm/contracts/gorm_dbcontext.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
package contracts

import (
"context"

"gorm.io/gorm"
)

type IGormDBContext interface {
WithTx(ctx context.Context) (IGormDBContext, error)
WithTxIfExists(ctx context.Context) IGormDBContext
RunInTx(ctx context.Context, action ActionFunc) error
DB() *gorm.DB
}

type ActionFunc func(ctx context.Context, gormContext IGormDBContext) error
Original file line number Diff line number Diff line change
Expand Up @@ -90,7 +90,9 @@ func createSQLLiteDB(dbFilePath string) (*gorm.DB, error) {
return gormSQLLiteDB, err
}

func NewSQLDB(orm *gorm.DB) (*sql.DB, error) { return orm.DB() }
func NewSQLDB(orm *gorm.DB) (*sql.DB, error) {
return orm.DB()
}

func createPostgresDB(cfg *GormOptions) error {
var db *sql.DB
Expand Down
1 change: 1 addition & 0 deletions internal/pkg/postgresgorm/gorm_postgres_fx.go
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@ var Module = fx.Module(
provideConfig,
NewGorm,
NewSQLDB,

fx.Annotate(
NewGormHealthChecker,
fx.As(new(contracts.Health)),
Expand Down
93 changes: 93 additions & 0 deletions internal/pkg/postgresgorm/gormdbcontext/gorm_dbcontext.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,93 @@
package gormdbcontext

import (
"context"

defaultlogger "github.com/mehdihadeli/go-ecommerce-microservices/internal/pkg/logger/defaultlogger"
"github.com/mehdihadeli/go-ecommerce-microservices/internal/pkg/postgresgorm/contracts"
"github.com/mehdihadeli/go-ecommerce-microservices/internal/pkg/postgresgorm/helpers/gormextensions"

"gorm.io/gorm"
)

type gormDBContext struct {
db *gorm.DB
}

func NewGormDBContext(db *gorm.DB) contracts.IGormDBContext {
c := &gormDBContext{db: db}

return c
}

func (c *gormDBContext) DB() *gorm.DB {
return c.db
}

// WithTx creates a transactional DBContext with getting tx-gorm from the ctx. This will throw an error if the transaction does not exist.
func (c *gormDBContext) WithTx(
ctx context.Context,
) (contracts.IGormDBContext, error) {
tx, err := gormextensions.GetTxFromContext(ctx)
if err != nil {
return nil, err
}

return NewGormDBContext(tx), nil
}

// WithTxIfExists creates a transactional DBContext with getting tx-gorm from the ctx. not throw an error if the transaction is not existing and returns an existing database.
func (c *gormDBContext) WithTxIfExists(
ctx context.Context,
) contracts.IGormDBContext {
tx := gormextensions.GetTxFromContextIfExists(ctx)
if tx == nil {
return c
}

return NewGormDBContext(tx)
}

func (c *gormDBContext) RunInTx(
ctx context.Context,
action contracts.ActionFunc,
) error {
// https://gorm.io/docs/transactions.html#Transaction
tx := c.DB().WithContext(ctx).Begin()

defaultlogger.GetLogger().Info("beginning database transaction")

gormContext := gormextensions.SetTxToContext(ctx, tx)
ctx = gormContext

defer func() {
if r := recover(); r != nil {
tx.WithContext(ctx).Rollback()

if err, _ := r.(error); err != nil {
defaultlogger.GetLogger().Errorf(
"panic tn the transaction, rolling back transaction with panic err: %+v",
err,
)
} else {
defaultlogger.GetLogger().Errorf("panic tn the transaction, rolling back transaction with panic message: %+v", r)
}
}
}()

err := action(ctx, c)
if err != nil {
defaultlogger.GetLogger().Error("rolling back transaction")
tx.WithContext(ctx).Rollback()

return err
}

defaultlogger.GetLogger().Info("committing transaction")

if err = tx.WithContext(ctx).Commit().Error; err != nil {
defaultlogger.GetLogger().Errorf("transaction commit error: %+v", err)
}

return err
}
Loading

0 comments on commit 6c00afc

Please sign in to comment.