youtu_server/game_open_api/model/app_user_model.go

61 lines
1.6 KiB
Go
Raw Normal View History

2025-01-20 01:55:44 +08:00
package model
import (
2025-01-20 14:37:14 +08:00
"context"
"fmt"
2025-01-20 01:55:44 +08:00
"github.com/zeromicro/go-zero/core/stores/cache"
2025-01-20 14:37:14 +08:00
"github.com/zeromicro/go-zero/core/stores/sqlc"
2025-01-20 01:55:44 +08:00
"github.com/zeromicro/go-zero/core/stores/sqlx"
)
var _ AppUserModel = (*customAppUserModel)(nil)
type (
// AppUserModel is an interface to be customized, add more methods here,
// and implement the added methods in customAppUserModel.
AppUserModel interface {
appUserModel
2025-01-20 14:37:14 +08:00
FindOrCreate(ctx context.Context, data *AppUser) (err error)
2025-01-20 01:55:44 +08:00
}
customAppUserModel struct {
*defaultAppUserModel
}
)
2025-01-23 16:14:23 +08:00
const cacheEcpmAppUserPrefix = "cache:ecpm:appUser:"
2025-01-20 01:55:44 +08:00
// NewAppUserModel returns a model for the database table.
func NewAppUserModel(conn sqlx.SqlConn, c cache.CacheConf, opts ...cache.Option) AppUserModel {
return &customAppUserModel{
defaultAppUserModel: newAppUserModel(conn, c, opts...),
}
}
2025-01-20 14:37:14 +08:00
func (m *customAppUserModel) FindOrCreate(ctx context.Context, data *AppUser) (err error) {
2025-01-23 16:14:23 +08:00
ecpmAppUserIdKey := fmt.Sprintf("%sappId:%d:openid:%s", cacheEcpmAppUserPrefix, data.AppAccountId, data.Openid)
2025-01-20 14:37:14 +08:00
var resp AppUser
err = m.QueryRowCtx(ctx, &resp, ecpmAppUserIdKey, func(ctx context.Context, conn sqlx.SqlConn, v any) error {
2025-01-23 16:14:23 +08:00
query := "select * from app_user where `openid` = ? and `app_account_id`= ? limit 1"
return conn.QueryRowCtx(ctx, v, query, data.Openid, data.AppAccountId)
2025-01-20 14:37:14 +08:00
})
switch err {
case nil:
*data = resp
return nil
case sqlc.ErrNotFound:
res, err := m.Insert(ctx, data)
if err != nil {
return err
}
id, err := res.LastInsertId()
if err != nil {
return err
}
data.Id = uint64(id)
return nil
default:
return err
}
}