Skip to content
Toggle navigation
P
Projects
G
Groups
S
Snippets
Help
phsl
/
new-api
This project
Loading...
Sign in
Toggle navigation
Go to a project
Project
Repository
Issues
0
Merge Requests
0
Pipelines
Wiki
Snippets
Members
Activity
Graph
Charts
Create a new issue
Jobs
Commits
Issue Boards
Files
Commits
Branches
Tags
Contributors
Graph
Compare
Charts
Commit
7765aa1d
authored
Jul 07, 2023
by
JustSong
Browse files
Options
Browse Files
Download
Email Patches
Plain Diff
fix: use transaction to protect redeem process
parent
d644150c
Show whitespace changes
Inline
Side-by-side
Showing
1 changed file
with
11 additions
and
9 deletions
+11
-9
model/redemption.go
+11
-9
No files found.
model/redemption.go
View file @
7765aa1d
...
@@ -3,6 +3,7 @@ package model
...
@@ -3,6 +3,7 @@ package model
import
(
import
(
"errors"
"errors"
"fmt"
"fmt"
"gorm.io/gorm"
"one-api/common"
"one-api/common"
)
)
...
@@ -48,26 +49,27 @@ func Redeem(key string, userId int) (quota int, err error) {
...
@@ -48,26 +49,27 @@ func Redeem(key string, userId int) (quota int, err error) {
return
0
,
errors
.
New
(
"无效的 user id"
)
return
0
,
errors
.
New
(
"无效的 user id"
)
}
}
redemption
:=
&
Redemption
{}
redemption
:=
&
Redemption
{}
err
=
DB
.
Where
(
"`key` = ?"
,
key
)
.
First
(
redemption
)
.
Error
err
=
DB
.
Transaction
(
func
(
tx
*
gorm
.
DB
)
error
{
err
:=
DB
.
Where
(
"`key` = ?"
,
key
)
.
First
(
redemption
)
.
Error
if
err
!=
nil
{
if
err
!=
nil
{
return
0
,
errors
.
New
(
"无效的兑换码"
)
return
errors
.
New
(
"无效的兑换码"
)
}
}
if
redemption
.
Status
!=
common
.
RedemptionCodeStatusEnabled
{
if
redemption
.
Status
!=
common
.
RedemptionCodeStatusEnabled
{
return
0
,
errors
.
New
(
"该兑换码已被使用"
)
return
errors
.
New
(
"该兑换码已被使用"
)
}
}
err
=
IncreaseUserQuota
(
userId
,
redemption
.
Quota
)
err
=
DB
.
Model
(
&
User
{})
.
Where
(
"id = ?"
,
userId
)
.
Update
(
"quota"
,
gorm
.
Expr
(
"quota + ?"
,
redemption
.
Quota
))
.
Error
if
err
!=
nil
{
if
err
!=
nil
{
return
0
,
err
return
err
}
}
go
func
()
{
redemption
.
RedeemedTime
=
common
.
GetTimestamp
()
redemption
.
RedeemedTime
=
common
.
GetTimestamp
()
redemption
.
Status
=
common
.
RedemptionCodeStatusUsed
redemption
.
Status
=
common
.
RedemptionCodeStatusUsed
err
:=
redemption
.
SelectUpdate
()
return
redemption
.
SelectUpdate
()
})
if
err
!=
nil
{
if
err
!=
nil
{
common
.
SysError
(
"failed to update redemption status:
"
+
err
.
Error
())
return
0
,
errors
.
New
(
"兑换失败,
"
+
err
.
Error
())
}
}
RecordLog
(
userId
,
LogTypeTopup
,
fmt
.
Sprintf
(
"通过兑换码充值 %s"
,
common
.
LogQuota
(
redemption
.
Quota
)))
RecordLog
(
userId
,
LogTypeTopup
,
fmt
.
Sprintf
(
"通过兑换码充值 %s"
,
common
.
LogQuota
(
redemption
.
Quota
)))
}()
return
redemption
.
Quota
,
nil
return
redemption
.
Quota
,
nil
}
}
...
...
Write
Preview
Markdown
is supported
0%
Try again
or
attach a new file
Attach a file
Cancel
You are about to add
0
people
to the discussion. Proceed with caution.
Finish editing this message first!
Cancel
Please
register
or
sign in
to comment