59 lines
1.5 KiB
Go
59 lines
1.5 KiB
Go
package model
|
|
|
|
import (
|
|
"context"
|
|
"fmt"
|
|
"github.com/zeromicro/go-zero/core/stores/cache"
|
|
"github.com/zeromicro/go-zero/core/stores/sqlc"
|
|
"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
|
|
FindOrCreate(ctx context.Context, data *AppUser) (err error)
|
|
}
|
|
|
|
customAppUserModel struct {
|
|
*defaultAppUserModel
|
|
}
|
|
)
|
|
|
|
// 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...),
|
|
}
|
|
}
|
|
|
|
func (m *customAppUserModel) FindOrCreate(ctx context.Context, data *AppUser) (err error) {
|
|
ecpmAppUserIdKey := fmt.Sprintf("%s%v", cacheEcpmAppUserIdPrefix, data.Id)
|
|
var resp AppUser
|
|
err = m.QueryRowCtx(ctx, &resp, ecpmAppUserIdKey, func(ctx context.Context, conn sqlx.SqlConn, v any) error {
|
|
query := fmt.Sprintf("select %s from %s where `openid` = ? limit 1", appUserRows, m.table)
|
|
return conn.QueryRowCtx(ctx, v, query, data.Openid)
|
|
})
|
|
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
|
|
}
|
|
}
|