Skip to content

Commit

Permalink
fix: fix redemption can be used multiple times in some cases
Browse files Browse the repository at this point in the history
  • Loading branch information
songquanpeng committed Jul 23, 2023
1 parent 4eea096 commit 889af8b
Showing 1 changed file with 4 additions and 3 deletions.
7 changes: 4 additions & 3 deletions model/redemption.go
Original file line number Diff line number Diff line change
Expand Up @@ -51,20 +51,21 @@ func Redeem(key string, userId int) (quota int, err error) {
redemption := &Redemption{}

err = DB.Transaction(func(tx *gorm.DB) error {
err := DB.Where("`key` = ?", key).First(redemption).Error
err := tx.Set("gorm:query_option", "FOR UPDATE").Where("`key` = ?", key).First(redemption).Error
if err != nil {
return errors.New("无效的兑换码")
}
if redemption.Status != common.RedemptionCodeStatusEnabled {
return errors.New("该兑换码已被使用")
}
err = DB.Model(&User{}).Where("id = ?", userId).Update("quota", gorm.Expr("quota + ?", redemption.Quota)).Error
err = tx.Model(&User{}).Where("id = ?", userId).Update("quota", gorm.Expr("quota + ?", redemption.Quota)).Error
if err != nil {
return err
}
redemption.RedeemedTime = common.GetTimestamp()
redemption.Status = common.RedemptionCodeStatusUsed
return redemption.SelectUpdate()
err = tx.Save(redemption).Error
return err
})
if err != nil {
return 0, errors.New("兑换失败," + err.Error())
Expand Down

0 comments on commit 889af8b

Please sign in to comment.