go-rest-api icon indicating copy to clipboard operation
go-rest-api copied to clipboard

How to use transactional in services?

Open kolkov opened this issue 4 years ago • 1 comments

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

kolkov avatar Feb 26 '20 21:02 kolkov

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
    })
}

kolkov avatar Feb 26 '20 22:02 kolkov