Файли
2026-11-08 03:05:46 +00:00

55 рядки
1.2 KiB
Go

package repository
import (
"context"
"errors"
"fmt"
"gorm.io/gorm"
"git.entityseven.com/rilaxik/pllist/internal/domain"
)
type UserRepository struct {
db *gorm.DB
}
func NewUserRepository(db *gorm.DB) *UserRepository {
return &UserRepository{db: db}
}
func (r *UserRepository) Ensure(ctx context.Context, telegramID int64) (domain.User, error) {
model := UserModel{TelegramID: telegramID}
err := r.db.WithContext(ctx).
Where("telegram_id = ?", telegramID).
FirstOrCreate(&model).
Error
if err != nil {
return domain.User{}, fmt.Errorf("ensure user: %w", err)
}
return userToDomain(model), nil
}
func (r *UserRepository) GetByTelegramID(
ctx context.Context, telegramID int64,
) (domain.User, bool, error) {
var model UserModel
err := r.db.WithContext(ctx).Where("telegram_id = ?", telegramID).First(&model).Error
if errors.Is(err, gorm.ErrRecordNotFound) {
return domain.User{}, false, nil
}
if err != nil {
return domain.User{}, false, fmt.Errorf("get user by telegram id: %w", err)
}
return userToDomain(model), true, nil
}
func userToDomain(model UserModel) domain.User {
return domain.User{
ID: model.ID,
TelegramID: model.TelegramID,
CreatedAt: model.CreatedAt,
UpdatedAt: model.UpdatedAt,
}
}