98 lines
2.5 KiB
Go
98 lines
2.5 KiB
Go
package ds
|
|
|
|
import (
|
|
"context"
|
|
|
|
"github.com/oklog/ulid/v2"
|
|
"github.com/timetracker/backend/internal/domain/entities"
|
|
"github.com/timetracker/backend/internal/domain/persistence"
|
|
"github.com/timetracker/backend/internal/infrastructure/persistence/db/dbo"
|
|
"gorm.io/gorm"
|
|
)
|
|
|
|
type UserDatasource struct {
|
|
db *gorm.DB
|
|
}
|
|
|
|
func NewUserDatasource(db *gorm.DB) persistence.UserDatasource {
|
|
return &UserDatasource{db: db}
|
|
}
|
|
|
|
func (r *UserDatasource) Get(ctx context.Context, id ulid.ULID) (*entities.User, error) {
|
|
var userDBO dbo.UserDBO
|
|
if err := r.db.WithContext(ctx).First(&userDBO, "id = ?", id).Error; err != nil {
|
|
return nil, err
|
|
}
|
|
|
|
user := &entities.User{
|
|
EntityBase: entities.EntityBase{
|
|
ID: userDBO.ID,
|
|
CreatedAt: userDBO.CreatedAt,
|
|
UpdatedAt: userDBO.UpdatedAt,
|
|
},
|
|
Username: userDBO.Username,
|
|
Password: userDBO.Password,
|
|
Role: userDBO.Role,
|
|
CompanyID: userDBO.CompanyID,
|
|
HourlyRate: userDBO.HourlyRate,
|
|
}
|
|
|
|
return user, nil
|
|
}
|
|
|
|
func (r *UserDatasource) Create(ctx context.Context, user *entities.User) error {
|
|
userDBO := dbo.UserDBO{
|
|
ID: user.ID,
|
|
CreatedAt: user.CreatedAt,
|
|
UpdatedAt: user.UpdatedAt,
|
|
Username: user.Username,
|
|
Password: user.Password,
|
|
Role: user.Role,
|
|
CompanyID: user.CompanyID,
|
|
HourlyRate: user.HourlyRate,
|
|
}
|
|
|
|
return r.db.WithContext(ctx).Create(&userDBO).Error
|
|
}
|
|
|
|
func (r *UserDatasource) Update(ctx context.Context, user *entities.User) error {
|
|
userDBO := dbo.UserDBO{
|
|
ID: user.ID,
|
|
CreatedAt: user.CreatedAt,
|
|
UpdatedAt: user.UpdatedAt,
|
|
Username: user.Username,
|
|
Password: user.Password,
|
|
Role: user.Role,
|
|
CompanyID: user.CompanyID,
|
|
HourlyRate: user.HourlyRate,
|
|
}
|
|
|
|
return r.db.WithContext(ctx).Save(&userDBO).Error
|
|
}
|
|
|
|
func (r *UserDatasource) Delete(ctx context.Context, id ulid.ULID) error {
|
|
return r.db.WithContext(ctx).Delete(&dbo.UserDBO{}, "id = ?", id).Error
|
|
}
|
|
|
|
func (r *UserDatasource) GetByUsername(ctx context.Context, username string) (*entities.User, error) {
|
|
var userDBO dbo.UserDBO
|
|
if err := r.db.WithContext(ctx).Where("username = ?", username).First(&userDBO).Error; err != nil {
|
|
return nil, err
|
|
}
|
|
|
|
user := &entities.User{
|
|
EntityBase: entities.EntityBase{
|
|
ID: userDBO.ID,
|
|
CreatedAt: userDBO.CreatedAt,
|
|
UpdatedAt: userDBO.UpdatedAt,
|
|
},
|
|
Username: userDBO.Username,
|
|
Password: userDBO.Password,
|
|
Role: userDBO.Role,
|
|
CompanyID: userDBO.CompanyID,
|
|
HourlyRate: userDBO.HourlyRate,
|
|
}
|
|
|
|
return user, nil
|
|
}
|