Created
February 3, 2018 13:12
-
-
Save patricksuo/a53e067603000206e1f62d722a733e63 to your computer and use it in GitHub Desktop.
This file contains hidden or 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
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