Loggest thine Stuff
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 
 
 

73 lines
1.7 KiB

package scopes
import (
"context"
"git.aiterp.net/stufflog3/stufflog3/entities"
"git.aiterp.net/stufflog3/stufflog3/models"
"git.aiterp.net/stufflog3/stufflog3/usecases/auth"
)
type Service struct {
Auth *auth.Service
Repository Repository
contextKey struct{}
}
func (s *Service) ContextWithScope(ctx context.Context, scope entities.Scope) context.Context {
return context.WithValue(ctx, &s.contextKey, &scope)
}
func (s *Service) ScopeFromContext(ctx context.Context) *entities.Scope {
v := ctx.Value(&s.contextKey)
if v == nil {
return nil
}
return v.(*entities.Scope)
}
// Find finds a scope and its members, and returns it if the logged-in user is part of this list.
func (s *Service) Find(ctx context.Context, id int) (*entities.Scope, []entities.ScopeMember, error) {
scope, err := s.Repository.Find(ctx, id)
if err != nil {
return nil, nil, err
}
members, err := s.Repository.ListMembers(ctx, scope.ID)
if err != nil {
return nil, nil, err
}
userID := s.Auth.GetUser(ctx)
found := false
for _, member := range members {
if member.UserID == userID {
found = true
break
}
}
if !found {
return nil, nil, models.NotFoundError("Scope")
}
return scope, members, nil
}
// List lists a scope and their members, and returns it if the logged-in user is part of this list.
func (s *Service) List(ctx context.Context) ([]entities.Scope, []entities.ScopeMember, error) {
scopes, err := s.Repository.ListUser(ctx, s.Auth.GetUser(ctx))
if err != nil {
return nil, nil, err
}
ids := make([]int, 0, len(scopes))
for _, scope := range scopes {
ids = append(ids, scope.ID)
}
members, err := s.Repository.ListMembers(ctx, ids...)
if err != nil {
return nil, nil, err
}
return scopes, members, nil
}