go-todo-api/services/todo_implementation.go
2025-12-02 18:58:25 +08:00

65 lines
2.1 KiB
Go
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

package services
import (
"go-todo-api/models"
"go-todo-api/repositories"
)
// TodoServiceImpl 结构体持有 TodoRepository 接口,实现业务逻辑
type TodoServiceImpl struct {
// Repo 字段是 Repository 接口类型,而不是具体实现
Repo repositories.TodoRepository
}
// NewTodoService 实例化一个新的 TodoService
func NewTodoService(repo repositories.TodoRepository) TodoService {
return &TodoServiceImpl{Repo: repo}
}
// FindAllTodos 实现了 Service 接口,直接调用 Repository
func (s *TodoServiceImpl) FindAllTodos(userID uint) ([]models.Todo, error) {
// 业务逻辑(例如:权限检查、数据缓存等)会在这里添加
// ❗ 修正:将 userID 传递给 Repo
return s.Repo.FindAll(userID)
}
// FindTodoByID 实现了 Service 接口,并处理 Repository 可能返回的错误
func (s *TodoServiceImpl) FindTodoByID(id uint, userID uint) (*models.Todo, error) {
// 调用 Repository 查找数据
return s.Repo.FindByID(id, userID)
}
// DeleteTodoByID 实现了 Service 接口的删除方法
func (s *TodoServiceImpl) DeleteTodoByID(id uint, userID uint) error {
// ❗ 调用 Repository 层执行删除
return s.Repo.Delete(id, userID)
}
// CreateTodo 实现了 Service 接口的创建方法
func (s *TodoServiceImpl) CreateTodo(todo *models.Todo, userID uint) error {
// 1. 设置 UserID (这是业务逻辑,在 Service 层完成)
todo.UserID = userID
// ❗ 调用 Repository 层执行创建
return s.Repo.Create(todo)
}
// UpdateTodo 实现了 Service 接口的更新方法
func (s *TodoServiceImpl) UpdateTodo(id uint, userID uint, input map[string]interface{}) (*models.Todo, error) {
// 1. 先查找记录Repository层 FindByID 已经实现了)
// ❗ 修正:将 userID 传递给 FindByID
todo, err := s.Repo.FindByID(id, userID)
if err != nil {
// 如果未找到或有其他错误,直接返回
return nil, err
}
// 2. 使用 Repository 层执行更新
// 2. Repository 层执行更新 (Repository 不需知道 UserID因为它操作的是已找到的 todo 对象)
if err := s.Repo.Update(todo, input); err != nil {
return nil, err
}
// 3. 返回更新后的对象
return todo, nil
}