105 lines
1.8 KiB
Go
105 lines
1.8 KiB
Go
package training
|
|
|
|
import (
|
|
"context"
|
|
"sync"
|
|
)
|
|
|
|
type InMemoryRepository struct {
|
|
m sync.Mutex
|
|
nextID ID
|
|
|
|
trainings map[ID]*Training
|
|
}
|
|
|
|
type InMemoryPricingRepository struct{}
|
|
|
|
func NewInMemoryRepository() *InMemoryRepository {
|
|
return &InMemoryRepository{
|
|
m: sync.Mutex{},
|
|
nextID: 1,
|
|
trainings: make(map[ID]*Training),
|
|
}
|
|
}
|
|
|
|
func (r *InMemoryRepository) FindAll(_ context.Context) ([]Training, error) {
|
|
r.m.Lock()
|
|
defer r.m.Unlock()
|
|
|
|
var trainings []Training
|
|
for _, t := range r.trainings {
|
|
trainings = append(trainings, *t)
|
|
}
|
|
|
|
return trainings, nil
|
|
}
|
|
|
|
func (r *InMemoryRepository) FindByID(_ context.Context, id ID) (*Training, error) {
|
|
r.m.Lock()
|
|
defer r.m.Unlock()
|
|
|
|
t, ok := r.trainings[id]
|
|
if !ok {
|
|
return nil, &ErrNotFound{}
|
|
}
|
|
return t, nil
|
|
}
|
|
|
|
func (r *InMemoryRepository) Create(_ context.Context, training *Training) error {
|
|
r.m.Lock()
|
|
defer r.m.Unlock()
|
|
|
|
training.id = r.nextID
|
|
r.nextID++
|
|
r.trainings[training.id] = training
|
|
|
|
return nil
|
|
}
|
|
|
|
func (r *InMemoryRepository) Update(_ context.Context, training *Training) error {
|
|
r.m.Lock()
|
|
defer r.m.Unlock()
|
|
|
|
if _, ok := r.trainings[training.id]; !ok {
|
|
return &ErrNotFound{}
|
|
}
|
|
|
|
r.trainings[training.id] = training
|
|
return nil
|
|
}
|
|
|
|
func (r *InMemoryRepository) Publish(_ context.Context, id ID) error {
|
|
r.m.Lock()
|
|
defer r.m.Unlock()
|
|
|
|
t, ok := r.trainings[id]
|
|
if !ok {
|
|
return &ErrNotFound{}
|
|
}
|
|
t.published = true
|
|
return nil
|
|
}
|
|
|
|
func (r *InMemoryRepository) Unpublish(_ context.Context, id ID) error {
|
|
r.m.Lock()
|
|
defer r.m.Unlock()
|
|
|
|
t, ok := r.trainings[id]
|
|
if !ok {
|
|
return &ErrNotFound{}
|
|
}
|
|
t.published = false
|
|
return nil
|
|
}
|
|
|
|
func (r *InMemoryRepository) Retire(_ context.Context, id ID) error {
|
|
r.m.Lock()
|
|
defer r.m.Unlock()
|
|
|
|
t, ok := r.trainings[id]
|
|
if !ok {
|
|
return &ErrNotFound{}
|
|
}
|
|
t.retired = true
|
|
return nil
|
|
}
|