70 lines
1.9 KiB
Go
70 lines
1.9 KiB
Go
package graph
|
|
|
|
import (
|
|
"context"
|
|
"errors"
|
|
"fmt"
|
|
"tailly_back_v2/internal/domain"
|
|
"tailly_back_v2/internal/repository"
|
|
"time"
|
|
)
|
|
|
|
type deviceResolver struct{ *Resolver }
|
|
|
|
// Device returns DeviceResolver implementation.
|
|
func (r *Resolver) Device() DeviceResolver { return &deviceResolver{r} }
|
|
|
|
// LastActiveAt is the resolver for the lastActiveAt field.
|
|
func (r *deviceResolver) LastActiveAt(ctx context.Context, obj *domain.Device) (string, error) {
|
|
if obj == nil {
|
|
return "", fmt.Errorf("device is nil")
|
|
}
|
|
// Используем ExpiresAt как время последней активности
|
|
return obj.ExpiresAt.Format(time.RFC3339), nil
|
|
}
|
|
|
|
// RenameDevice is the resolver for the renameDevice field.
|
|
func (r *mutationResolver) RenameDevice(ctx context.Context, deviceID int, name string) (*domain.Device, error) {
|
|
userID, err := getUserIDFromContext(ctx)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
|
|
// Получаем устройство через репозиторий
|
|
device, err := r.DeviceRepo.GetByID(ctx, deviceID)
|
|
if err != nil {
|
|
if errors.Is(err, repository.ErrDeviceNotFound) {
|
|
return nil, fmt.Errorf("device not found")
|
|
}
|
|
return nil, fmt.Errorf("failed to get device: %v", err)
|
|
}
|
|
|
|
// Проверяем владельца устройства
|
|
if device.UserID != userID {
|
|
return nil, fmt.Errorf("unauthorized to rename this device")
|
|
}
|
|
|
|
// Обновляем имя
|
|
device.Name = name
|
|
if err := r.DeviceRepo.Update(ctx, device); err != nil {
|
|
return nil, fmt.Errorf("failed to update device: %v", err)
|
|
}
|
|
|
|
return device, nil
|
|
}
|
|
|
|
// Devices is the resolver for the devices field.
|
|
func (r *queryResolver) Devices(ctx context.Context) ([]*domain.Device, error) {
|
|
userID, err := getUserIDFromContext(ctx)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
|
|
devices, err := r.DeviceRepo.GetByUser(ctx, userID)
|
|
if err != nil {
|
|
return nil, fmt.Errorf("failed to get user devices: %v", err)
|
|
}
|
|
|
|
return devices, nil
|
|
}
|