106 рядки
2.6 KiB
Go
106 рядки
2.6 KiB
Go
package repository
|
|
|
|
import (
|
|
"context"
|
|
"errors"
|
|
"fmt"
|
|
|
|
"gorm.io/gorm"
|
|
|
|
"git.entityseven.com/rilaxik/pllist/internal/domain"
|
|
)
|
|
|
|
type ListRepository struct {
|
|
db *gorm.DB
|
|
}
|
|
|
|
func NewListRepository(db *gorm.DB) *ListRepository {
|
|
return &ListRepository{db: db}
|
|
}
|
|
|
|
func (r *ListRepository) Create(ctx context.Context, ownerID int64, title string) (domain.List, error) {
|
|
model := ListModel{OwnerID: ownerID, Title: title}
|
|
if err := r.db.WithContext(ctx).Create(&model).Error; err != nil {
|
|
return domain.List{}, fmt.Errorf("create list: %w", err)
|
|
}
|
|
return listToDomain(model), nil
|
|
}
|
|
|
|
func (r *ListRepository) Get(ctx context.Context, id int64) (domain.List, error) {
|
|
var model ListModel
|
|
err := r.db.WithContext(ctx).First(&model, id).Error
|
|
if errors.Is(err, gorm.ErrRecordNotFound) {
|
|
return domain.List{}, domain.ErrNotFound
|
|
}
|
|
if err != nil {
|
|
return domain.List{}, fmt.Errorf("get list: %w", err)
|
|
}
|
|
return listToDomain(model), nil
|
|
}
|
|
|
|
func (r *ListRepository) ListForUser(ctx context.Context, userID int64) ([]domain.List, error) {
|
|
shared := r.db.Model(&ListShareModel{}).
|
|
Select("list_id").
|
|
Where("user_id = ?", userID)
|
|
|
|
var models []ListModel
|
|
err := r.db.WithContext(ctx).
|
|
Where("owner_id = ? OR id IN (?)", userID, shared).
|
|
Order("updated_at DESC").
|
|
Find(&models).
|
|
Error
|
|
if err != nil {
|
|
return nil, fmt.Errorf("list lists for user: %w", err)
|
|
}
|
|
|
|
lists := make([]domain.List, len(models))
|
|
for i, model := range models {
|
|
lists[i] = listToDomain(model)
|
|
}
|
|
return lists, nil
|
|
}
|
|
|
|
func (r *ListRepository) Rename(ctx context.Context, id int64, title string) error {
|
|
err := r.db.WithContext(ctx).
|
|
Model(&ListModel{}).
|
|
Where("id = ?", id).
|
|
Update("title", title).
|
|
Error
|
|
if err != nil {
|
|
return fmt.Errorf("rename list: %w", err)
|
|
}
|
|
return nil
|
|
}
|
|
|
|
func (r *ListRepository) Delete(ctx context.Context, id int64) error {
|
|
if err := r.db.WithContext(ctx).Delete(&ListModel{}, id).Error; err != nil {
|
|
return fmt.Errorf("delete list: %w", err)
|
|
}
|
|
return nil
|
|
}
|
|
|
|
func (r *ListRepository) Role(ctx context.Context, listID, userID int64) (domain.Role, bool, error) {
|
|
var model ListShareModel
|
|
err := r.db.WithContext(ctx).
|
|
Where("list_id = ? AND user_id = ?", listID, userID).
|
|
First(&model).
|
|
Error
|
|
if errors.Is(err, gorm.ErrRecordNotFound) {
|
|
return "", false, nil
|
|
}
|
|
if err != nil {
|
|
return "", false, fmt.Errorf("get list role: %w", err)
|
|
}
|
|
return domain.Role(model.Role), true, nil
|
|
}
|
|
|
|
func listToDomain(model ListModel) domain.List {
|
|
return domain.List{
|
|
ID: model.ID,
|
|
OwnerID: model.OwnerID,
|
|
Title: model.Title,
|
|
CreatedAt: model.CreatedAt,
|
|
UpdatedAt: model.UpdatedAt,
|
|
}
|
|
}
|