99 lines
2.3 KiB
Go
99 lines
2.3 KiB
Go
package repository
|
|
|
|
import (
|
|
"context"
|
|
"git.hlsq.asia/mmorpg/service-common/db/redis"
|
|
"git.hlsq.asia/mmorpg/service-user/internal/dao/model"
|
|
"git.hlsq.asia/mmorpg/service-user/internal/dao/query"
|
|
"time"
|
|
)
|
|
|
|
type UserDao struct {
|
|
ctx context.Context
|
|
query *query.Query
|
|
cache *redis.CacheClient
|
|
}
|
|
|
|
func NewUserDao(ctx context.Context, query *query.Query, cache ...*redis.CacheClient) *UserDao {
|
|
dao := &UserDao{
|
|
ctx: ctx,
|
|
query: query,
|
|
}
|
|
if len(cache) > 0 {
|
|
dao.cache = cache[0]
|
|
}
|
|
return dao
|
|
}
|
|
|
|
func (d *UserDao) Create(user *model.User) (*model.User, error) {
|
|
err := d.query.User.WithContext(d.ctx).
|
|
Create(user)
|
|
return user, err
|
|
}
|
|
|
|
func (d *UserDao) Updates(user *model.User) error {
|
|
info, _ := d.query.User.WithContext(d.ctx).
|
|
Where(d.query.User.ID.Eq(user.ID)).
|
|
Updates(user)
|
|
if info.RowsAffected > 0 {
|
|
if d.cache != nil {
|
|
d.cache.Del(d.ctx, keyCacheBySn(user.Sn, user.TableName()))
|
|
d.cache.Del(d.ctx, keyUserCacheByPhone(user.Phone))
|
|
}
|
|
}
|
|
return info.Error
|
|
}
|
|
|
|
func (d *UserDao) FindBySn(sn int64) (*model.User, error) {
|
|
if d.cache != nil {
|
|
var user model.User
|
|
if ok := d.cache.Get(d.ctx, keyCacheBySn(sn, user.TableName()), &user); ok {
|
|
return &user, nil
|
|
}
|
|
}
|
|
first, err := d.query.User.WithContext(d.ctx).
|
|
Where(d.query.User.Sn.Eq(sn)).
|
|
First()
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
if d.cache != nil {
|
|
d.cache.Set(d.ctx, keyCacheBySn(sn, first.TableName()), first, 5*time.Minute)
|
|
}
|
|
return first, nil
|
|
}
|
|
|
|
func (d *UserDao) FindByPhone(phone string) (*model.User, error) {
|
|
if d.cache != nil {
|
|
var user model.User
|
|
if ok := d.cache.Get(d.ctx, keyUserCacheByPhone(phone), &user); ok {
|
|
return &user, nil
|
|
}
|
|
}
|
|
first, err := d.query.User.WithContext(d.ctx).
|
|
Where(d.query.User.Phone.Eq(phone)).
|
|
First()
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
if d.cache != nil {
|
|
d.cache.Set(d.ctx, keyUserCacheByPhone(phone), first, 5*time.Minute)
|
|
}
|
|
return first, nil
|
|
}
|
|
|
|
// FindByWxUnionIDOrOpenID 通过微信unionID或openID查找用户
|
|
func (d *UserDao) FindByWxUnionIDOrOpenID(unionID, openID string) (*model.User, error) {
|
|
q := d.query.User.WithContext(d.ctx)
|
|
if unionID != "" {
|
|
q = q.Where(d.query.User.WxUnionID.Eq(unionID))
|
|
} else {
|
|
q = q.Where(d.query.User.WxMiniOpenID.Eq(openID))
|
|
}
|
|
first, err := q.First()
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
return first, nil
|
|
}
|