Skip to content

Commit

Permalink
✨ Added API route for querying single task
Browse files Browse the repository at this point in the history
  • Loading branch information
Luke Carr committed Apr 8, 2022
1 parent b3e70d7 commit 8b4e600
Show file tree
Hide file tree
Showing 2 changed files with 45 additions and 2 deletions.
32 changes: 30 additions & 2 deletions internal/routes/task.go
Original file line number Diff line number Diff line change
@@ -1,25 +1,53 @@
package routes

import (
"strconv"

"github.com/gofiber/fiber/v2"
"github.com/lukecarr/tiny-todo/internal/env"
"github.com/rs/zerolog/log"
)

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 {
return func(c *fiber.Ctx) error {
tasks, err := e.Services.Task.GetAll()

if err != nil {
log.Error().Err(err).Send()
return err
}

Expand Down
15 changes: 15 additions & 0 deletions internal/services/task.go
Original file line number Diff line number Diff line change
@@ -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)
Expand All @@ -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\"")
Expand Down

0 comments on commit 8b4e600

Please sign in to comment.