2022-02-10 22:06:57 +00:00
|
|
|
//go:build !change
|
2020-03-19 21:57:07 +00:00
|
|
|
|
|
|
|
package models
|
|
|
|
|
|
|
|
import (
|
|
|
|
"fmt"
|
|
|
|
"sync"
|
|
|
|
)
|
|
|
|
|
|
|
|
type Storage interface {
|
|
|
|
AddTodo(string, string) (*Todo, error)
|
|
|
|
GetTodo(ID) (*Todo, error)
|
|
|
|
GetAll() ([]*Todo, error)
|
2022-03-24 15:48:48 +00:00
|
|
|
FinishTodo(ID) error
|
2020-03-19 21:57:07 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
type InMemoryStorage struct {
|
|
|
|
mu sync.RWMutex
|
|
|
|
todos map[ID]*Todo
|
|
|
|
|
|
|
|
nextID ID
|
|
|
|
}
|
|
|
|
|
|
|
|
func NewInMemoryStorage() *InMemoryStorage {
|
|
|
|
return &InMemoryStorage{
|
|
|
|
todos: make(map[ID]*Todo),
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
func (s *InMemoryStorage) AddTodo(title, content string) (*Todo, error) {
|
|
|
|
s.mu.Lock()
|
|
|
|
defer s.mu.Unlock()
|
|
|
|
|
|
|
|
id := s.nextID
|
|
|
|
s.nextID++
|
|
|
|
|
|
|
|
todo := &Todo{
|
|
|
|
ID: id,
|
|
|
|
Title: title,
|
|
|
|
Content: content,
|
|
|
|
Finished: false,
|
|
|
|
}
|
|
|
|
|
|
|
|
s.todos[todo.ID] = todo
|
|
|
|
|
|
|
|
return todo, nil
|
|
|
|
}
|
|
|
|
|
|
|
|
func (s *InMemoryStorage) GetTodo(id ID) (*Todo, error) {
|
|
|
|
s.mu.RLock()
|
|
|
|
defer s.mu.RUnlock()
|
|
|
|
|
|
|
|
todo, ok := s.todos[id]
|
|
|
|
if !ok {
|
|
|
|
return nil, fmt.Errorf("todo %d not found", id)
|
|
|
|
}
|
|
|
|
|
|
|
|
return todo, nil
|
|
|
|
}
|
|
|
|
|
|
|
|
func (s *InMemoryStorage) GetAll() ([]*Todo, error) {
|
|
|
|
s.mu.RLock()
|
|
|
|
defer s.mu.RUnlock()
|
|
|
|
|
|
|
|
var out []*Todo
|
|
|
|
for _, todo := range s.todos {
|
|
|
|
out = append(out, todo)
|
|
|
|
}
|
|
|
|
|
|
|
|
return out, nil
|
|
|
|
}
|
2022-03-24 15:48:48 +00:00
|
|
|
|
|
|
|
func (s *InMemoryStorage) FinishTodo(id ID) error {
|
|
|
|
s.mu.Lock()
|
|
|
|
defer s.mu.Unlock()
|
|
|
|
|
|
|
|
todo, ok := s.todos[id]
|
|
|
|
if !ok {
|
|
|
|
return fmt.Errorf("todo %d not found", id)
|
|
|
|
}
|
|
|
|
|
|
|
|
todo.MarkFinished()
|
|
|
|
return nil
|
|
|
|
}
|