Last active
August 1, 2019 01:15
-
-
Save jfeng45/8ea86be9862ea94f8de5c2add96479f7 to your computer and use it in GitHub Desktop.
the business logic in transaction
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// The use case of ModifyAndUnregister without transaction | |
func (ruc *RegistrationUseCase) ModifyAndUnregister(user *model.User) error { | |
return modifyAndUnregister(ruc, user) | |
} | |
// The use case of ModifyAndUnregister with transaction | |
func (ruc *RegistrationUseCase) ModifyAndUnregisterWithTx(user *model.User) error { | |
tdi, err := ruc.TxDataInterface.TxBegin() | |
if err != nil { | |
return errors.Wrap(err, "") | |
} | |
ruc.EnableTx() | |
return tdi.TxEnd(func() error { | |
// wrap the business function inside the TxEnd function | |
return modifyAndUnregister(ruc, user) | |
}) | |
} | |
// The business function will be wrapped inside a transaction and inside a non-transaction function | |
// It needs to be written in a way that every error will be returned so it can be catched by TxEnd() function, | |
// which will handle commit and rollback | |
func modifyAndUnregister(ruc *RegistrationUseCase, user *model.User) error { | |
udi := ruc.UserDataInterface | |
err := modifyUser(udi, user) | |
if err != nil { | |
return errors.Wrap(err, "") | |
} | |
err = unregisterUser(udi, user.Name) | |
if err != nil { | |
return errors.Wrap(err, "") | |
} | |
return nil | |
} | |
func (ruc *RegistrationUseCase) EnableTx() { | |
// Only UserDataInterface need transaction support here. If there are other data services need it, | |
// then they also need to enable transaction here | |
ruc.UserDataInterface.EnableTx(ruc.TxDataInterface) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment