Skip to content

Instantly share code, notes, and snippets.

@patricksuo
Created February 3, 2018 13:12
Show Gist options
  • Save patricksuo/a53e067603000206e1f62d722a733e63 to your computer and use it in GitHub Desktop.
Save patricksuo/a53e067603000206e1f62d722a733e63 to your computer and use it in GitHub Desktop.
func BuyHandler(buyRequest BuyRequest) {
for i:=0; i<MaxRetry; i++ {
needRetry := func() (retry bool) {
defer func() {
if err := recover(); err != nil {
if _, isTxConflic := err.(ErrTransactionConflic); isTxConflic {
retry = true;
}
}
}()
BuyLogic();
return retry
}()
if !needRetry {
return;
}
}
}
func BuyLogic(accountKey, goodsID int64) {
tx = db.Begin()
account, err := tx.LoadEntity(EntityType_Account, accountKey)
if err != nil {
panic(err)
}
goods, err := tx.LoadEntity(EntityType_Goods, goodsID)
if err != nil {
panic(err)
}
goodsDetail := goods.Detail.Lookup()
if goodsDetail.Stocks <= 0 {
tx.Rollback();
return status.StockNotEnough("blablabla");
}
credit := account.Credit.Lookup()
if goodsDetail.Price > credit.Balance {
tx.Rollback()
return status.BalanceNotEnough("blablabla")
}
goodsDetail.Stocks--
credit.Balance -= goodsDetail.Price
goods.Detail.Update(goodsDetail)
account.Credit.Update(credit)
tx.Commit()
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment