fix: auth flow fixed, add getOrCreate method for user
This commit is contained in:
@@ -4,11 +4,19 @@ import (
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
type Base struct {
|
||||
ID uuid.UUID
|
||||
ID uuid.UUID `gorm:"type:uuid;default:uuid_generate_v4();primaryKey"`
|
||||
CreatedAt time.Time
|
||||
UpdatedAt time.Time
|
||||
DeletedAt *time.Time
|
||||
}
|
||||
|
||||
func (b *Base) BeforeCreate(tx *gorm.DB) (err error) {
|
||||
if b.ID == uuid.Nil {
|
||||
b.ID = uuid.New()
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
@@ -27,6 +27,7 @@ func CastUserToStorage(u domain.User) *User {
|
||||
UpdatedAt: u.UpdatedAt,
|
||||
DeletedAt: u.DeletedAt,
|
||||
},
|
||||
PubKey: u.PubKey,
|
||||
Name: u.Name,
|
||||
LastName: u.LastName,
|
||||
Phone: u.PhoneNumber,
|
||||
@@ -40,6 +41,7 @@ func CastUserToStorage(u domain.User) *User {
|
||||
func CastUserToDomain(u User) *domain.User {
|
||||
return &domain.User{
|
||||
ID: u.ID,
|
||||
PubKey: u.PubKey,
|
||||
Name: u.Name,
|
||||
LastName: u.LastName,
|
||||
PhoneNumber: u.Phone,
|
||||
|
||||
@@ -20,8 +20,12 @@ func NewUserRepository(db *gorm.DB) domain.UserRepo {
|
||||
}
|
||||
|
||||
func (r *UserRepository) Create(ctx context.Context, user *domain.User) error {
|
||||
var model types.User
|
||||
return r.db.WithContext(ctx).Create(&model).Error
|
||||
model := types.CastUserToStorage(*user)
|
||||
if err := r.db.WithContext(ctx).Create(model).Error; err != nil {
|
||||
return err
|
||||
}
|
||||
*user = *types.CastUserToDomain(*model)
|
||||
return nil
|
||||
}
|
||||
|
||||
func (r *UserRepository) GetByID(ctx context.Context, id uuid.UUID) (*domain.User, error) {
|
||||
@@ -56,3 +60,22 @@ func (r *UserRepository) GetByPubKey(ctx context.Context, pubKey string) (*domai
|
||||
}
|
||||
return types.CastUserToDomain(user), nil
|
||||
}
|
||||
|
||||
func (r *UserRepository) GetOrCreateUserByPubKey(ctx context.Context, pubKey string) (*domain.User, error) {
|
||||
var user types.User
|
||||
err := r.db.WithContext(ctx).First(&user, "pub_key = ?", pubKey).Error
|
||||
if err == nil {
|
||||
return types.CastUserToDomain(user), nil
|
||||
}
|
||||
if err != gorm.ErrRecordNotFound {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
user = types.User{
|
||||
PubKey: pubKey,
|
||||
}
|
||||
if err := r.db.WithContext(ctx).Create(&user).Error; err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return types.CastUserToDomain(user), nil
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user