homebox/backend/internal/services/service_locations.go

77 lines
1.9 KiB
Go
Raw Normal View History

2022-08-31 03:21:18 +00:00
package services
import (
"context"
2022-09-01 22:32:03 +00:00
"errors"
2022-08-31 03:21:18 +00:00
"github.com/google/uuid"
"github.com/hay-kot/homebox/backend/internal/repo"
"github.com/hay-kot/homebox/backend/internal/services/mappers"
"github.com/hay-kot/homebox/backend/internal/types"
2022-08-31 03:21:18 +00:00
)
2022-09-01 22:32:03 +00:00
var (
ErrNotOwner = errors.New("not owner")
)
2022-08-31 03:21:18 +00:00
type LocationService struct {
repos *repo.AllRepos
}
2022-09-01 22:32:03 +00:00
func (svc *LocationService) GetOne(ctx context.Context, groupId uuid.UUID, id uuid.UUID) (*types.LocationOut, error) {
location, err := svc.repos.Locations.Get(ctx, id)
2022-08-31 03:21:18 +00:00
2022-09-01 22:32:03 +00:00
if err != nil {
return nil, err
}
if location.Edges.Group.ID != groupId {
return nil, ErrNotOwner
}
return mappers.ToLocationOut(location), nil
2022-08-31 05:22:01 +00:00
}
2022-09-03 09:17:48 +00:00
func (svc *LocationService) GetAll(ctx context.Context, groupId uuid.UUID) ([]*types.LocationCount, error) {
2022-08-31 05:22:01 +00:00
locations, err := svc.repos.Locations.GetAll(ctx, groupId)
if err != nil {
return nil, err
}
2022-09-03 09:17:48 +00:00
locationsOut := make([]*types.LocationCount, len(locations))
2022-08-31 05:22:01 +00:00
for i, location := range locations {
2022-09-03 09:17:48 +00:00
locationsOut[i] = mappers.ToLocationCount(&location)
2022-08-31 05:22:01 +00:00
}
return locationsOut, nil
2022-08-31 03:21:18 +00:00
}
2022-09-01 22:32:03 +00:00
2022-09-03 09:17:48 +00:00
func (svc *LocationService) Create(ctx context.Context, groupId uuid.UUID, data types.LocationCreate) (*types.LocationOut, error) {
2022-09-01 22:32:03 +00:00
location, err := svc.repos.Locations.Create(ctx, groupId, data)
2022-09-03 09:17:48 +00:00
return mappers.ToLocationOutErr(location, err)
2022-09-01 22:32:03 +00:00
}
func (svc *LocationService) Delete(ctx context.Context, groupId uuid.UUID, id uuid.UUID) error {
location, err := svc.repos.Locations.Get(ctx, id)
if err != nil {
return err
}
if location.Edges.Group.ID != groupId {
return ErrNotOwner
}
return svc.repos.Locations.Delete(ctx, id)
}
func (svc *LocationService) Update(ctx context.Context, groupId uuid.UUID, data types.LocationUpdate) (*types.LocationOut, error) {
location, err := svc.repos.Locations.Get(ctx, data.ID)
if err != nil {
return nil, err
}
if location.Edges.Group.ID != groupId {
return nil, ErrNotOwner
}
return mappers.ToLocationOutErr(svc.repos.Locations.Update(ctx, data))
}