package todo
import (
"context"
"fmt"
"sync"
)
// Service is the todo service.
type Service struct {
mu sync.RWMutex
todos map[string]*Todo
nextID int
}
// New creates a new todo service.
func New() *Service {
return &Service{
todos: make(map[string]*Todo),
}
}
// Todo is a todo item.
type Todo struct {
ID string `json:"id"`
Title string `json:"title"`
Completed bool `json:"completed"`
}
// CreateInput is the input for creating a todo.
type CreateInput struct {
Title string `json:"title"`
}
// Create creates a new todo.
func (s *Service) Create(ctx context.Context, in *CreateInput) (*Todo, error) {
s.mu.Lock()
defer s.mu.Unlock()
s.nextID++
todo := &Todo{
ID: fmt.Sprintf("%d", s.nextID),
Title: in.Title,
}
s.todos[todo.ID] = todo
return todo, nil
}
// List returns all todos.
func (s *Service) List(ctx context.Context) ([]*Todo, error) {
s.mu.RLock()
defer s.mu.RUnlock()
todos := make([]*Todo, 0, len(s.todos))
for _, t := range s.todos {
todos = append(todos, t)
}
return todos, nil
}