github.com/ars0915/glossika-exercise@v0.0.0-20240904180321-a5617a00d892/repo/handler.go (about)

     1  package repo
     2  
     3  import "context"
     4  
     5  type txKey struct{}
     6  
     7  // injectTx injects transaction to context
     8  func InjectTx(ctx context.Context, tx App) context.Context {
     9  	return context.WithValue(ctx, txKey{}, tx)
    10  }
    11  
    12  // extractTx extracts transaction from context
    13  func ExtractTx(ctx context.Context) App {
    14  	if tx, ok := ctx.Value(txKey{}).(App); ok {
    15  		return tx
    16  	}
    17  	return nil
    18  }
    19  
    20  func WithinTransaction(ctx context.Context, s App, tFunc func(ctx context.Context) error) error {
    21  	var isNewTx bool
    22  	tx := ExtractTx(ctx)
    23  	// there is no tx inject to ctx, so new one
    24  	if tx == nil {
    25  		tx = s.Begin()
    26  		defer tx.Rollback()
    27  		isNewTx = true
    28  	}
    29  
    30  	// run callback
    31  	if err := tFunc(InjectTx(ctx, tx)); err != nil {
    32  		return err
    33  	}
    34  
    35  	// tx extract from ctx don't need commit
    36  	if isNewTx {
    37  		return tx.Commit()
    38  	}
    39  	return nil
    40  }