Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

How to use transactional in services? #6

Open
kolkov opened this issue Feb 26, 2020 · 1 comment
Open

How to use transactional in services? #6

kolkov opened this issue Feb 26, 2020 · 1 comment

Comments

@kolkov
Copy link

kolkov commented Feb 26, 2020

Hi! Please provide en complex example about using treansactional in services.
Existing example in readme is very abstract... (
Thanks!

@kolkov kolkov changed the title How to use transactionl in services? How to use transactional in services? Feb 26, 2020
@kolkov
Copy link
Author

kolkov commented Feb 26, 2020

Is this correct?

func main() {
	// ...
		// connect to the database
		db, err := dbx.MustOpen("mysql", cfg.DSN)
		if err != nil {
			fmt.Println(err)
			os.Exit(-1)
		}
		dbc := dbcontext.New(db)
		txnFn := dbc.Transactional

		repo := pkg1.NewRepo(dbc)
		service := pkg1.NewService(repo, txnFN)
	}
}

service package

type service struct {
   repo Repository
   txnFn dbcontext.TransactionFunc
}

...
func(s service) SomeServiceMethod(ctx context.Context) error {
   err := serviceMethod(ctx, s.repo, s.txnFn)
   if err != nil {
      return err
   }
}

func serviceMethod(ctx context.Context, repo Repository, transactional dbcontext.TransactionFunc) error {
    return transactional(ctx, func(ctx context.Context) error {
        repo.method1(...)
        repo.method2(...)
        return nil
    })
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant