Skip to content

3. Protected CRUD Service (task) ​

Now we build the core task domain service. It demonstrates:

  • Cross-module DI: TaskRoutes injects *auth.AuthMiddleware directly from the auth module.
  • Custom validator/v10 rules: task_priority and task_status rules registered in core/validator.
  • Context-aware GORM queries: gormDB.WithContext(ctx) and strict user-ownership scoping (WHERE id = ? AND user_id = ?).
  • Canonical AppError handling: ErrNotFound, ErrConflict, ErrUnprocessable routed through middleware.ErrorHandler().
  • Custom Config injection: Enforcing cfg.Task.MaxPerUser from Chapter 1.

3.1 Scaffold the task Service ​

bash
goforge gen:service task

This creates internal/services/task/ and internal/proto/task/task.proto, and regenerates internal/services/kernel.go so Modules() includes both auth.Module() and task.Module().


3.2 Models (internal/services/task/model.go) ​

Define Task (scoped by UserID) and TaskAuditLog (used in Chapter 5 for async event auditing):

go
package task

import "time"

// Task represents a user-owned task item.
type Task struct {
	ID          uint64     `gorm:"primaryKey;autoIncrement" json:"id"`
	UserID      uint64     `gorm:"not null;index" json:"user_id"`
	Title       string     `gorm:"size:200;not null" json:"title"`
	Description string     `gorm:"type:text" json:"description"`
	Priority    string     `gorm:"size:16;not null;default:medium" json:"priority"`
	Status      string     `gorm:"size:16;not null;default:todo;index" json:"status"`
	DueDate     *time.Time `json:"due_date,omitempty"`
	CreatedAt   time.Time  `json:"created_at"`
	UpdatedAt   time.Time  `json:"updated_at"`
}

// TaskAuditLog records task lifecycle events asynchronously.
type TaskAuditLog struct {
	ID        uint64    `gorm:"primaryKey;autoIncrement" json:"id"`
	Action    string    `gorm:"size:64;not null" json:"action"`
	TaskID    uint64    `gorm:"not null;index" json:"task_id"`
	UserID    uint64    `gorm:"not null;index" json:"user_id"`
	Note      string    `gorm:"type:text" json:"note"`
	CreatedAt time.Time `json:"created_at"`
}

3.3 Custom Validation Rules (internal/services/task/validation.go) ​

GoForge's core/validator uses a dedicated validator/v10 instance reading validate: struct tags and JSON field names. Register custom rules for task_priority and task_status:

go
package task

import (
	"slices"

	corevalidator "github.com/acme/taskforge/core/validator"
	"github.com/go-playground/validator/v10"
)

var (
	allowedPriorities = []string{"low", "medium", "high"}
	allowedStatuses   = []string{"todo", "in_progress", "done"}
)

func init() {
	_ = corevalidator.RegisterRuleWithMessage(
		"task_priority",
		func(fl validator.FieldLevel) bool {
			return slices.Contains(allowedPriorities, fl.Field().String())
		},
		"{0} must be one of: low, medium, high",
	)

	_ = corevalidator.RegisterRuleWithMessage(
		"task_status",
		func(fl validator.FieldLevel) bool {
			return slices.Contains(allowedStatuses, fl.Field().String())
		},
		"{0} must be one of: todo, in_progress, done",
	)
}

3.4 Business Logic (internal/services/task/service.go) ​

TaskService receives *database.Database, *events.EventBus, and *config.AllConfig via DI. Every query is scoped to userID and honors ctx:

go
package task

import (
	"context"
	"errors"
	"fmt"
	"time"

	"github.com/acme/taskforge/core/config"
	"github.com/acme/taskforge/core/database"
	apperrors "github.com/acme/taskforge/core/errors"
	"github.com/acme/taskforge/core/events"
	"gorm.io/gorm"
)

type ListFilter struct {
	Status   string
	Priority string
	Limit    int
	Offset   int
}

type TaskService struct {
	db  *database.Database
	bus *events.EventBus
	cfg *config.AllConfig
}

func NewTaskService(db *database.Database, bus *events.EventBus, cfg *config.AllConfig) *TaskService {
	return &TaskService{db: db, bus: bus, cfg: cfg}
}

func (s *TaskService) ListByUser(ctx context.Context, userID uint64, filter ListFilter) ([]Task, error) {
	gormDB, err := s.db.GetGorm()
	if err != nil {
		return nil, apperrors.ErrInternalServer("database unavailable").Wrap(err)
	}

	limit := filter.Limit
	if limit <= 0 || limit > 100 {
		limit = 20
	}

	q := gormDB.WithContext(ctx).Where("user_id = ?", userID)
	if filter.Status != "" {
		q = q.Where("status = ?", filter.Status)
	}
	if filter.Priority != "" {
		q = q.Where("priority = ?", filter.Priority)
	}

	var tasks []Task
	if err := q.Order("created_at DESC").Limit(limit).Offset(filter.Offset).Find(&tasks).Error; err != nil {
		return nil, apperrors.ErrInternalServer("failed to list tasks").Wrap(err)
	}
	return tasks, nil
}

func (s *TaskService) GetByIDForUser(ctx context.Context, userID, taskID uint64) (*Task, error) {
	gormDB, err := s.db.GetGorm()
	if err != nil {
		return nil, apperrors.ErrInternalServer("database unavailable").Wrap(err)
	}

	var t Task
	if err := gormDB.WithContext(ctx).Where("id = ? AND user_id = ?", taskID, userID).First(&t).Error; err != nil {
		if errors.Is(err, gorm.ErrRecordNotFound) {
			return nil, apperrors.ErrNotFound(fmt.Sprintf("task %d not found", taskID))
		}
		return nil, apperrors.ErrInternalServer("failed to fetch task").Wrap(err)
	}
	return &t, nil
}

func (s *TaskService) Create(ctx context.Context, userID uint64, title, description, priority string, dueDate *time.Time) (*Task, error) {
	gormDB, err := s.db.GetGorm()
	if err != nil {
		return nil, apperrors.ErrInternalServer("database unavailable").Wrap(err)
	}

	var count int64
	if err := gormDB.WithContext(ctx).Model(&Task{}).Where("user_id = ?", userID).Count(&count).Error; err != nil {
		return nil, apperrors.ErrInternalServer("failed to check task quota").Wrap(err)
	}
	if s.cfg != nil && s.cfg.Task.MaxPerUser > 0 && int(count) >= s.cfg.Task.MaxPerUser {
		return nil, apperrors.ErrConflict(fmt.Sprintf("task limit (%d) reached", s.cfg.Task.MaxPerUser))
	}

	if priority == "" {
		priority = "medium"
	}

	t := &Task{
		UserID:      userID,
		Title:       title,
		Description: description,
		Priority:    priority,
		Status:      "todo",
		DueDate:     dueDate,
	}
	if err := gormDB.WithContext(ctx).Create(t).Error; err != nil {
		return nil, apperrors.ErrInternalServer("failed to create task").Wrap(err)
	}

	// Event dispatch will be added in Chapter 5
	return t, nil
}

func (s *TaskService) Update(ctx context.Context, userID, taskID uint64, title, description, priority, status string, dueDate *time.Time) (*Task, error) {
	t, err := s.GetByIDForUser(ctx, userID, taskID)
	if err != nil {
		return nil, err
	}

	if title != "" {
		t.Title = title
	}
	if description != "" {
		t.Description = description
	}
	if priority != "" {
		t.Priority = priority
	}
	if status != "" {
		t.Status = status
	}
	if dueDate != nil {
		t.DueDate = dueDate
	}

	gormDB, err := s.db.GetGorm()
	if err != nil {
		return nil, apperrors.ErrInternalServer("database unavailable").Wrap(err)
	}
	if err := gormDB.WithContext(ctx).Save(t).Error; err != nil {
		return nil, apperrors.ErrInternalServer("failed to update task").Wrap(err)
	}
	return t, nil
}

func (s *TaskService) Complete(ctx context.Context, userID, taskID uint64) (*Task, error) {
	return s.Update(ctx, userID, taskID, "", "", "", "done", nil)
}

func (s *TaskService) Delete(ctx context.Context, userID, taskID uint64) error {
	gormDB, err := s.db.GetGorm()
	if err != nil {
		return apperrors.ErrInternalServer("database unavailable").Wrap(err)
	}

	res := gormDB.WithContext(ctx).Where("id = ? AND user_id = ?", taskID, userID).Delete(&Task{})
	if res.Error != nil {
		return apperrors.ErrInternalServer("failed to delete task").Wrap(res.Error)
	}
	if res.RowsAffected == 0 {
		return apperrors.ErrNotFound(fmt.Sprintf("task %d not found", taskID))
	}
	return nil
}

3.5 HTTP Handler (internal/services/task/handler.go) ​

go
package task

import (
	"net/http"
	"strconv"
	"time"

	apperrors "github.com/acme/taskforge/core/errors"
	corevalidator "github.com/acme/taskforge/core/validator"
	"github.com/acme/taskforge/internal/services/auth"
	"github.com/gin-gonic/gin"
)

type CreateTaskRequest struct {
	Title       string     `json:"title" validate:"required,min=1,max=200"`
	Description string     `json:"description" validate:"max=2000"`
	Priority    string     `json:"priority" validate:"omitempty,task_priority"`
	DueDate     *time.Time `json:"due_date,omitempty"`
}

type UpdateTaskRequest struct {
	Title       string     `json:"title" validate:"omitempty,min=1,max=200"`
	Description string     `json:"description" validate:"max=2000"`
	Priority    string     `json:"priority" validate:"omitempty,task_priority"`
	Status      string     `json:"status" validate:"omitempty,task_status"`
	DueDate     *time.Time `json:"due_date,omitempty"`
}

type TaskHandler struct {
	service *TaskService
}

func NewTaskHandler(service *TaskService) *TaskHandler {
	return &TaskHandler{service: service}
}

func (h *TaskHandler) List(c *gin.Context) {
	userID, ok := auth.UserIDFromContext(c)
	if !ok {
		_ = c.Error(apperrors.ErrUnauthorized("authentication required"))
		return
	}

	limit, _ := strconv.Atoi(c.Query("limit"))
	offset, _ := strconv.Atoi(c.Query("offset"))

	tasks, err := h.service.ListByUser(c.Request.Context(), userID, ListFilter{
		Status:   c.Query("status"),
		Priority: c.Query("priority"),
		Limit:    limit,
		Offset:   offset,
	})
	if err != nil {
		_ = c.Error(err)
		return
	}
	c.JSON(http.StatusOK, gin.H{"data": tasks})
}

func (h *TaskHandler) GetByID(c *gin.Context) {
	userID, ok := auth.UserIDFromContext(c)
	if !ok {
		_ = c.Error(apperrors.ErrUnauthorized("authentication required"))
		return
	}

	id, err := strconv.ParseUint(c.Param("id"), 10, 64)
	if err != nil || id == 0 {
		_ = c.Error(apperrors.ErrBadRequest("invalid task id"))
		return
	}

	t, err := h.service.GetByIDForUser(c.Request.Context(), userID, id)
	if err != nil {
		_ = c.Error(err)
		return
	}
	c.JSON(http.StatusOK, gin.H{"data": t})
}

func (h *TaskHandler) Create(c *gin.Context) {
	userID, ok := auth.UserIDFromContext(c)
	if !ok {
		_ = c.Error(apperrors.ErrUnauthorized("authentication required"))
		return
	}

	var req CreateTaskRequest
	if err := c.ShouldBindJSON(&req); err != nil {
		_ = c.Error(apperrors.ErrBadRequest("invalid JSON payload"))
		return
	}
	if appErr := corevalidator.Validate(req); appErr != nil {
		_ = c.Error(appErr)
		return
	}

	t, err := h.service.Create(c.Request.Context(), userID, req.Title, req.Description, req.Priority, req.DueDate)
	if err != nil {
		_ = c.Error(err)
		return
	}
	c.JSON(http.StatusCreated, gin.H{"data": t})
}

func (h *TaskHandler) Update(c *gin.Context) {
	userID, ok := auth.UserIDFromContext(c)
	if !ok {
		_ = c.Error(apperrors.ErrUnauthorized("authentication required"))
		return
	}

	id, err := strconv.ParseUint(c.Param("id"), 10, 64)
	if err != nil || id == 0 {
		_ = c.Error(apperrors.ErrBadRequest("invalid task id"))
		return
	}

	var req UpdateTaskRequest
	if err := c.ShouldBindJSON(&req); err != nil {
		_ = c.Error(apperrors.ErrBadRequest("invalid JSON payload"))
		return
	}
	if appErr := corevalidator.Validate(req); appErr != nil {
		_ = c.Error(appErr)
		return
	}

	t, err := h.service.Update(c.Request.Context(), userID, id, req.Title, req.Description, req.Priority, req.Status, req.DueDate)
	if err != nil {
		_ = c.Error(err)
		return
	}
	c.JSON(http.StatusOK, gin.H{"data": t})
}

func (h *TaskHandler) Complete(c *gin.Context) {
	userID, ok := auth.UserIDFromContext(c)
	if !ok {
		_ = c.Error(apperrors.ErrUnauthorized("authentication required"))
		return
	}

	id, err := strconv.ParseUint(c.Param("id"), 10, 64)
	if err != nil || id == 0 {
		_ = c.Error(apperrors.ErrBadRequest("invalid task id"))
		return
	}

	t, err := h.service.Complete(c.Request.Context(), userID, id)
	if err != nil {
		_ = c.Error(err)
		return
	}
	c.JSON(http.StatusOK, gin.H{"data": t})
}

func (h *TaskHandler) Delete(c *gin.Context) {
	userID, ok := auth.UserIDFromContext(c)
	if !ok {
		_ = c.Error(apperrors.ErrUnauthorized("authentication required"))
		return
	}

	id, err := strconv.ParseUint(c.Param("id"), 10, 64)
	if err != nil || id == 0 {
		_ = c.Error(apperrors.ErrBadRequest("invalid task id"))
		return
	}

	if err := h.service.Delete(c.Request.Context(), userID, id); err != nil {
		_ = c.Error(err)
		return
	}
	c.Status(http.StatusNoContent)
}

3.6 Protected Routes & Module (routes.go & module.go) ​

NewTaskRoutes injects *auth.AuthMiddleware across modules and applies RequireAuth() to the /api/tasks group:

go
// internal/services/task/routes.go
package task

import (
	"github.com/acme/taskforge/internal/services/auth"
	"github.com/gin-gonic/gin"
)

type TaskRoutes struct {
	handler *TaskHandler
	authMW  *auth.AuthMiddleware
}

func NewTaskRoutes(handler *TaskHandler, authMW *auth.AuthMiddleware) *TaskRoutes {
	return &TaskRoutes{handler: handler, authMW: authMW}
}

func (r *TaskRoutes) Register(engine *gin.Engine) {
	group := engine.Group("/api/tasks")
	group.Use(r.authMW.RequireAuth())

	group.GET("", r.handler.List)
	group.POST("", r.handler.Create)
	group.GET("/:id", r.handler.GetByID)
	group.PUT("/:id", r.handler.Update)
	group.PATCH("/:id/complete", r.handler.Complete)
	group.DELETE("/:id", r.handler.Delete)
}

Update internal/services/task/module.go to include both Task and TaskAuditLog:

go
package task

import "github.com/acme/taskforge/core/di"

func Module() di.Module {
	return di.Module{
		Name: "task",
		Providers: []any{
			NewTaskService,
			NewTaskHandler,
			NewTaskRoutes,
			NewTaskDocs,
		},
		Models: []any{
			&Task{},
			&TaskAuditLog{},
		},
	}
}

Next: 4. Migrations, SQLC & Seeders →

Released under the Apache-2.0 License.