61 lines
2.0 KiB
Cheetah
61 lines
2.0 KiB
Cheetah
package repository
|
|
|
|
import (
|
|
"context"
|
|
"sort"
|
|
"strconv"
|
|
"sync"
|
|
"time"
|
|
"{{.Module}}/internal/{{.Name}}/model"
|
|
)
|
|
|
|
type Repository interface {
|
|
Create(context.Context,string) (model.Item,error)
|
|
Get(context.Context,string) (model.Item,error)
|
|
List(context.Context) ([]model.Item,error)
|
|
Update(context.Context,string,string) (model.Item,error)
|
|
Delete(context.Context,string) error
|
|
}
|
|
|
|
// Memory is demonstration storage; data and IDs reset with the process.
|
|
type Memory struct { mu sync.Mutex; next uint64; items map[string]model.Item }
|
|
func NewMemory() *Memory { return &Memory{items:make(map[string]model.Item)} }
|
|
func (m *Memory) Create(ctx context.Context, name string) (model.Item,error) {
|
|
m.mu.Lock(); defer m.mu.Unlock()
|
|
if err:=ctx.Err(); err!=nil {return model.Item{},err}
|
|
m.next++
|
|
item:=model.Item{ID:strconv.FormatUint(m.next,10),Name:name,CreatedAt:time.Now().UTC()}
|
|
m.items[item.ID]=item
|
|
return item,nil
|
|
}
|
|
func (m *Memory) Get(ctx context.Context,id string) (model.Item,error) {
|
|
m.mu.Lock(); defer m.mu.Unlock()
|
|
if err:=ctx.Err(); err!=nil {return model.Item{},err}
|
|
item,ok:=m.items[id]
|
|
if !ok {return model.Item{},model.ErrNotFound}
|
|
return item,nil
|
|
}
|
|
func (m *Memory) List(ctx context.Context) ([]model.Item,error) {
|
|
m.mu.Lock(); defer m.mu.Unlock()
|
|
if err:=ctx.Err(); err!=nil {return nil,err}
|
|
items:=make([]model.Item,0,len(m.items))
|
|
for _,item:=range m.items {items=append(items,item)}
|
|
sort.Slice(items,func(i,j int)bool{return items[i].ID<items[j].ID})
|
|
return items,nil
|
|
}
|
|
func (m *Memory) Update(ctx context.Context,id,name string) (model.Item,error) {
|
|
m.mu.Lock(); defer m.mu.Unlock()
|
|
if err:=ctx.Err(); err!=nil {return model.Item{},err}
|
|
item,ok:=m.items[id]
|
|
if !ok {return model.Item{},model.ErrNotFound}
|
|
item.Name=name; m.items[id]=item
|
|
return item,nil
|
|
}
|
|
func (m *Memory) Delete(ctx context.Context,id string) error {
|
|
m.mu.Lock(); defer m.mu.Unlock()
|
|
if err:=ctx.Err(); err!=nil {return err}
|
|
if _,ok:=m.items[id]; !ok {return model.ErrNotFound}
|
|
delete(m.items,id)
|
|
return nil
|
|
}
|