70 lines
1.6 KiB
Go
70 lines
1.6 KiB
Go
package programs
|
|
|
|
import (
|
|
"Yimaru-Backend/internal/domain"
|
|
"Yimaru-Backend/internal/ports"
|
|
"context"
|
|
"errors"
|
|
|
|
"github.com/jackc/pgx/v5"
|
|
)
|
|
|
|
var ErrProgramNotFound = errors.New("program not found")
|
|
|
|
type Service struct {
|
|
store ports.ProgramStore
|
|
}
|
|
|
|
func NewService(store ports.ProgramStore) *Service {
|
|
return &Service{store: store}
|
|
}
|
|
|
|
func (s *Service) Create(ctx context.Context, input domain.CreateProgramInput) (domain.Program, error) {
|
|
return s.store.CreateProgram(ctx, input)
|
|
}
|
|
|
|
func (s *Service) GetByID(ctx context.Context, id int64) (domain.Program, error) {
|
|
p, err := s.store.GetProgramByID(ctx, id)
|
|
if err != nil {
|
|
if errors.Is(err, pgx.ErrNoRows) {
|
|
return domain.Program{}, ErrProgramNotFound
|
|
}
|
|
return domain.Program{}, err
|
|
}
|
|
return p, nil
|
|
}
|
|
|
|
func (s *Service) List(ctx context.Context, limit, offset int32) ([]domain.Program, int64, error) {
|
|
if limit <= 0 {
|
|
limit = 20
|
|
}
|
|
if limit > 200 {
|
|
limit = 200
|
|
}
|
|
if offset < 0 {
|
|
offset = 0
|
|
}
|
|
return s.store.ListPrograms(ctx, limit, offset)
|
|
}
|
|
|
|
func (s *Service) Update(ctx context.Context, id int64, input domain.UpdateProgramInput) (domain.Program, error) {
|
|
p, err := s.store.UpdateProgram(ctx, id, input)
|
|
if err != nil {
|
|
if errors.Is(err, pgx.ErrNoRows) {
|
|
return domain.Program{}, ErrProgramNotFound
|
|
}
|
|
return domain.Program{}, err
|
|
}
|
|
return p, nil
|
|
}
|
|
|
|
func (s *Service) Delete(ctx context.Context, id int64) error {
|
|
if _, err := s.store.GetProgramByID(ctx, id); err != nil {
|
|
if errors.Is(err, pgx.ErrNoRows) {
|
|
return ErrProgramNotFound
|
|
}
|
|
return err
|
|
}
|
|
return s.store.DeleteProgram(ctx, id)
|
|
}
|