Files
query-orchestration/internal/client/update/update.go
T

106 lines
2.1 KiB
Go
Raw Normal View History

2025-04-22 19:57:35 +00:00
package clientupdate
2025-01-21 18:24:14 +00:00
import (
"context"
"errors"
"log/slog"
2025-03-05 12:05:46 +00:00
2025-04-22 19:57:35 +00:00
"queryorchestration/internal/client"
2025-01-21 18:24:14 +00:00
"queryorchestration/internal/database/repository"
2025-04-22 19:57:35 +00:00
"queryorchestration/internal/serviceconfig/queue"
"queryorchestration/internal/validation"
2025-06-02 10:44:45 +00:00
clientsyncrunner "queryorchestration/api/clientSyncRunner"
2025-01-21 18:24:14 +00:00
)
type Update struct {
Name *string
CanSync *bool
}
func (s *Service) Update(ctx context.Context, id string, entity *Update) error {
2025-04-22 19:57:35 +00:00
current, err := s.svc.Client.Get(ctx, id)
2025-01-21 18:24:14 +00:00
if err != nil {
return err
}
err = s.normalizeUpdateParams(id, current, entity)
2025-01-21 18:24:14 +00:00
if err != nil {
return err
}
err = s.submitUpdate(ctx, id, entity)
2025-01-21 18:24:14 +00:00
if err != nil {
return err
}
2025-04-22 19:57:35 +00:00
err = s.informUpdate(ctx, id, entity)
if err != nil {
return err
}
2025-01-21 18:24:14 +00:00
return nil
}
2025-04-22 19:57:35 +00:00
func (s *Service) informUpdate(ctx context.Context, id string, entity *Update) error {
if entity.CanSync == nil || !*entity.CanSync {
return nil
}
return s.cfg.SendToQueue(ctx, &queue.SendParams{
QueueURL: s.cfg.GetClientSyncURL(),
Body: clientsyncrunner.Body{
ClientID: id,
},
})
}
func (s *Service) submitUpdate(ctx context.Context, id string, entity *Update) error {
return s.cfg.ExecuteDBTransaction(ctx, func(ctx context.Context, q *repository.Queries) error {
id := id
if entity.Name != nil {
err := q.UpdateClient(ctx, &repository.UpdateClientParams{
Clientid: id,
Name: *entity.Name,
})
if err != nil {
return err
}
}
if entity.CanSync != nil {
err := q.AddClientCanSync(ctx, &repository.AddClientCanSyncParams{
Clientid: id,
Cansync: *entity.CanSync,
})
if err != nil {
return err
}
}
slog.Debug("client updated", "update", *entity)
return nil
})
}
2025-04-22 19:57:35 +00:00
func (s *Service) normalizeUpdateParams(id string, current *client.Client, entity *Update) error {
if entity == nil || current == nil || current.ID != id {
return errors.New("no updates presented")
2025-01-21 18:24:14 +00:00
}
2025-04-22 19:57:35 +00:00
err := current.NormalizeNameUpdate(&entity.Name)
2025-01-21 18:24:14 +00:00
if err != nil {
return err
2025-01-21 18:24:14 +00:00
}
2025-04-22 19:57:35 +00:00
current.NormalizeCanSyncUpdate(&entity.CanSync)
if validation.AreAllPointersNilExcept(entity) {
return errors.New("no updates presented")
}
2025-01-21 18:24:14 +00:00
return nil
2025-01-21 18:24:14 +00:00
}