You cannot select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
77 lines
2.1 KiB
Go
77 lines
2.1 KiB
Go
3 years ago
|
package model
|
||
|
|
||
|
import (
|
||
|
"context"
|
||
|
"fmt"
|
||
|
"git.noahlan.cn/northlan/ntools-go/gorm-zero/gormc"
|
||
|
"github.com/pkg/errors"
|
||
|
"gorm.io/gorm"
|
||
|
)
|
||
|
|
||
|
var _ UserIntegralModel = (*customUserIntegralModel)(nil)
|
||
|
|
||
|
type (
|
||
|
// UserIntegralModel is an interface to be customized, add more methods here,
|
||
|
// and implement the added methods in customUserIntegralModel.
|
||
|
UserIntegralModel interface {
|
||
|
userIntegralModel
|
||
|
Transact(ctx context.Context, tx *gorm.DB, fn func(tx *gorm.DB) error) error
|
||
|
InsertTx(ctx context.Context, tx *gorm.DB, data *UserIntegral) error
|
||
|
UpdateIntegralTx(ctx context.Context, tx *gorm.DB, userId, addon int64) error
|
||
|
FindIntegral(ctx context.Context, tx *gorm.DB, userId int64) (int64, error)
|
||
|
}
|
||
|
|
||
|
customUserIntegralModel struct {
|
||
|
*defaultUserIntegralModel
|
||
|
}
|
||
|
)
|
||
|
|
||
|
// NewUserIntegralModel returns a model for the database table.
|
||
|
func NewUserIntegralModel(conn *gorm.DB) UserIntegralModel {
|
||
|
return &customUserIntegralModel{
|
||
|
defaultUserIntegralModel: newUserIntegralModel(conn),
|
||
|
}
|
||
|
}
|
||
|
|
||
|
func (m *customUserIntegralModel) Transact(ctx context.Context, tx *gorm.DB, fn func(tx *gorm.DB) error) error {
|
||
|
return withTx(ctx, m.conn, tx).Transaction(fn)
|
||
|
}
|
||
|
|
||
|
func (m *customUserIntegralModel) InsertTx(ctx context.Context, tx *gorm.DB, data *UserIntegral) error {
|
||
|
err := withTx(ctx, m.conn, tx).Create(&data).Error
|
||
|
return err
|
||
|
}
|
||
|
|
||
|
func (m *customUserIntegralModel) UpdateIntegralTx(ctx context.Context, tx *gorm.DB, userId, change int64) error {
|
||
|
if change < 0 {
|
||
|
return errors.New("无法将积分更新至负数")
|
||
|
}
|
||
|
db := withTx(ctx, m.conn, tx)
|
||
|
|
||
|
result := db.Table(m.table).
|
||
|
Where("user_id = ?", userId).
|
||
|
Update("integral", change)
|
||
|
if result.Error != nil {
|
||
|
return result.Error
|
||
|
}
|
||
|
if result.RowsAffected == 0 {
|
||
|
return ErrRowsAffectedZero
|
||
|
}
|
||
|
return nil
|
||
|
}
|
||
|
|
||
|
func (m *customUserIntegralModel) FindIntegral(ctx context.Context, tx *gorm.DB, userId int64) (int64, error) {
|
||
|
var resp int64
|
||
|
err := withTx(ctx, m.conn, tx).Table(m.table).
|
||
|
Select(fmt.Sprintf("%s.integral", m.table)).
|
||
|
Where("user_id = ?", userId).Take(&resp).Error
|
||
|
switch err {
|
||
|
case nil:
|
||
|
return resp, nil
|
||
|
case gormc.ErrNotFound:
|
||
|
return 0, ErrNotFound
|
||
|
default:
|
||
|
return 0, err
|
||
|
}
|
||
|
}
|