diff --git a/internal/routes/task.go b/internal/routes/task.go index eab1eed..4b03747 100644 --- a/internal/routes/task.go +++ b/internal/routes/task.go @@ -1,6 +1,8 @@ package routes import ( + "strconv" + "github.com/gofiber/fiber/v2" "github.com/lukecarr/tiny-todo/internal/env" "github.com/rs/zerolog/log" @@ -8,10 +10,37 @@ import ( func Task(e *env.Env, r fiber.Router) { r.Get("/", getAllTasks(e)) + r.Post("/", createTask(e)) + + r.Get("/:id", getTask(e)) + r.Get("/incomplete", getIncomplete(e)) + r.Get("/complete", getComplete(e)) +} - r.Post("/", createTask(e)) +func getTask(e *env.Env) func(*fiber.Ctx) error { + return func(c *fiber.Ctx) error { + param := c.Params("id") + id, err := strconv.Atoi(param) + + if err != nil { + return err + } + + task, err := e.Services.Task.Get(id) + + if err != nil { + log.Error().Err(err).Send() + return err + } + + if task == nil { + return c.SendStatus(404) + } + + return c.JSON(task) + } } func getAllTasks(e *env.Env) func(*fiber.Ctx) error { @@ -19,7 +48,6 @@ func getAllTasks(e *env.Env) func(*fiber.Ctx) error { tasks, err := e.Services.Task.GetAll() if err != nil { - log.Error().Err(err).Send() return err } diff --git a/internal/services/task.go b/internal/services/task.go index 200d999..2226121 100644 --- a/internal/services/task.go +++ b/internal/services/task.go @@ -1,11 +1,15 @@ package services import ( + "database/sql" + "errors" + "github.com/jmoiron/sqlx" "github.com/lukecarr/tiny-todo/internal/models" ) type TaskService interface { + Get(id int) (*models.Task, error) GetAll() ([]*models.Task, error) GetIncomplete() ([]*models.Task, error) GetComplete() ([]*models.Task, error) @@ -16,6 +20,17 @@ type TaskServiceSql struct { Sqlx *sqlx.DB } +func (s TaskServiceSql) Get(id int) (*models.Task, error) { + var task models.Task + err := s.Sqlx.Get(&task, "SELECT * FROM \"task\" WHERE \"task\".\"id\" = $1", id) + + if err != nil && errors.Is(err, sql.ErrNoRows) { + return nil, nil + } + + return &task, err +} + func (s TaskServiceSql) GetAll() ([]*models.Task, error) { tasks := make([]*models.Task, 0) err := s.Sqlx.Select(&tasks, "SELECT * FROM \"task\"")