CUB-127: implement Control Center CRUD API in Go
This commit is contained in:
158
go-backend/internal/handler/agent.go
Normal file
158
go-backend/internal/handler/agent.go
Normal file
@@ -0,0 +1,158 @@
|
||||
// Package handler contains HTTP handlers for the Control Center API.
|
||||
// Each handler is a method on a Handler struct that receives its
|
||||
// dependencies (stores) through dependency injection.
|
||||
package handler
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"net/http"
|
||||
"time"
|
||||
|
||||
"code.cubecraftcreations.com/CubeCraft-Creations/Control-Center/go-backend/internal/models"
|
||||
"code.cubecraftcreations.com/CubeCraft-Creations/Control-Center/go-backend/internal/store"
|
||||
"github.com/go-chi/chi/v5"
|
||||
"github.com/go-playground/validator/v10"
|
||||
)
|
||||
|
||||
// Handler groups all route handlers and their dependencies.
|
||||
type Handler struct {
|
||||
AgentStore *store.AgentStore
|
||||
SessionStore *store.SessionStore
|
||||
TaskStore *store.TaskStore
|
||||
ProjectStore *store.ProjectStore
|
||||
validate *validator.Validate
|
||||
}
|
||||
|
||||
// NewHandler returns a fully wired Handler.
|
||||
func NewHandler(
|
||||
as *store.AgentStore,
|
||||
ss *store.SessionStore,
|
||||
ts *store.TaskStore,
|
||||
ps *store.ProjectStore,
|
||||
) *Handler {
|
||||
v := validator.New()
|
||||
v.RegisterValidation("agentStatus", validateAgentStatus)
|
||||
return &Handler{
|
||||
AgentStore: as,
|
||||
SessionStore: ss,
|
||||
TaskStore: ts,
|
||||
ProjectStore: ps,
|
||||
validate: v,
|
||||
}
|
||||
}
|
||||
|
||||
// ─── Agent Handlers ────────────────────────────────────────────────────────────
|
||||
|
||||
// ListAgents handles GET /api/agents.
|
||||
func (h *Handler) ListAgents(w http.ResponseWriter, r *http.Request) {
|
||||
statusFilter := models.AgentStatus(r.URL.Query().Get("status"))
|
||||
allAgents := h.AgentStore.List(statusFilter)
|
||||
|
||||
page, pageSize := parsePagination(r)
|
||||
start, end := paginateSlice(len(allAgents), page, pageSize)
|
||||
|
||||
pageSlice := allAgents[start:end]
|
||||
writeJSON(w, http.StatusOK, models.PaginatedResponse{
|
||||
Data: pageSlice,
|
||||
TotalCount: h.AgentStore.Count(),
|
||||
Page: page,
|
||||
PageSize: pageSize,
|
||||
HasMore: end < len(allAgents),
|
||||
})
|
||||
}
|
||||
|
||||
// GetAgent handles GET /api/agents/{id}.
|
||||
func (h *Handler) GetAgent(w http.ResponseWriter, r *http.Request) {
|
||||
id := chi.URLParam(r, "id")
|
||||
agent, ok := h.AgentStore.Get(id)
|
||||
if !ok {
|
||||
writeJSON(w, http.StatusNotFound, models.ErrorResponse{Error: "agent not found"})
|
||||
return
|
||||
}
|
||||
writeJSON(w, http.StatusOK, agent)
|
||||
}
|
||||
|
||||
// CreateAgent handles POST /api/agents.
|
||||
func (h *Handler) CreateAgent(w http.ResponseWriter, r *http.Request) {
|
||||
var req models.CreateAgentRequest
|
||||
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
|
||||
writeJSON(w, http.StatusBadRequest, models.ErrorResponse{Error: "invalid request body"})
|
||||
return
|
||||
}
|
||||
|
||||
if err := h.validate.Struct(req); err != nil {
|
||||
writeJSON(w, http.StatusUnprocessableEntity, models.ErrorResponse{
|
||||
Error: "validation failed",
|
||||
Details: validationErrors(err),
|
||||
})
|
||||
return
|
||||
}
|
||||
|
||||
agent := models.AgentCardData{
|
||||
ID: req.ID,
|
||||
DisplayName: req.DisplayName,
|
||||
Role: req.Role,
|
||||
Status: req.Status,
|
||||
CurrentTask: req.CurrentTask,
|
||||
SessionKey: req.SessionKey,
|
||||
Channel: req.Channel,
|
||||
LastActivity: time.Now().UTC().Format(time.RFC3339),
|
||||
}
|
||||
|
||||
if ok := h.AgentStore.Create(agent); !ok {
|
||||
writeJSON(w, http.StatusConflict, models.ErrorResponse{Error: "agent with this ID already exists"})
|
||||
return
|
||||
}
|
||||
writeJSON(w, http.StatusCreated, agent)
|
||||
}
|
||||
|
||||
// UpdateAgent handles PUT /api/agents/{id}.
|
||||
func (h *Handler) UpdateAgent(w http.ResponseWriter, r *http.Request) {
|
||||
id := chi.URLParam(r, "id")
|
||||
|
||||
var req models.UpdateAgentRequest
|
||||
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
|
||||
writeJSON(w, http.StatusBadRequest, models.ErrorResponse{Error: "invalid request body"})
|
||||
return
|
||||
}
|
||||
|
||||
if err := h.validate.Struct(req); err != nil {
|
||||
writeJSON(w, http.StatusUnprocessableEntity, models.ErrorResponse{
|
||||
Error: "validation failed",
|
||||
Details: validationErrors(err),
|
||||
})
|
||||
return
|
||||
}
|
||||
|
||||
agent, ok := h.AgentStore.Update(id, req)
|
||||
if !ok {
|
||||
writeJSON(w, http.StatusNotFound, models.ErrorResponse{Error: "agent not found"})
|
||||
return
|
||||
}
|
||||
writeJSON(w, http.StatusOK, agent)
|
||||
}
|
||||
|
||||
// DeleteAgent handles DELETE /api/agents/{id}.
|
||||
func (h *Handler) DeleteAgent(w http.ResponseWriter, r *http.Request) {
|
||||
id := chi.URLParam(r, "id")
|
||||
if ok := h.AgentStore.Delete(id); !ok {
|
||||
writeJSON(w, http.StatusNotFound, models.ErrorResponse{Error: "agent not found"})
|
||||
return
|
||||
}
|
||||
w.WriteHeader(http.StatusNoContent)
|
||||
}
|
||||
|
||||
// AgentHistory handles GET /api/agents/{id}/history.
|
||||
func (h *Handler) AgentHistory(w http.ResponseWriter, r *http.Request) {
|
||||
id := chi.URLParam(r, "id")
|
||||
if _, ok := h.AgentStore.Get(id); !ok {
|
||||
writeJSON(w, http.StatusNotFound, models.ErrorResponse{Error: "agent not found"})
|
||||
return
|
||||
}
|
||||
|
||||
history := h.AgentStore.History(id)
|
||||
if history == nil {
|
||||
history = []models.AgentStatusHistoryEntry{}
|
||||
}
|
||||
writeJSON(w, http.StatusOK, history)
|
||||
}
|
||||
369
go-backend/internal/handler/handler_test.go
Normal file
369
go-backend/internal/handler/handler_test.go
Normal file
@@ -0,0 +1,369 @@
|
||||
package handler
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"code.cubecraftcreations.com/CubeCraft-Creations/Control-Center/go-backend/internal/models"
|
||||
"code.cubecraftcreations.com/CubeCraft-Creations/Control-Center/go-backend/internal/store"
|
||||
"github.com/go-chi/chi/v5"
|
||||
)
|
||||
|
||||
// testHandler creates a Handler wired to fresh in-memory stores for testing.
|
||||
func testHandler(t *testing.T) *Handler {
|
||||
t.Helper()
|
||||
return NewHandler(
|
||||
store.NewAgentStore(),
|
||||
store.NewSessionStore(),
|
||||
store.NewTaskStore(),
|
||||
store.NewProjectStore(),
|
||||
)
|
||||
}
|
||||
|
||||
// serveChi creates a chi.Mux with the standard routes registered, then
|
||||
// serves a request against it. Returns the recorded response.
|
||||
func serveChi(h *Handler, method, path, body string) *httptest.ResponseRecorder {
|
||||
w := httptest.NewRecorder()
|
||||
req := httptest.NewRequest(method, path, strings.NewReader(body))
|
||||
req.Header.Set("Content-Type", "application/json")
|
||||
|
||||
r := chi.NewRouter()
|
||||
r.Route("/api", func(api chi.Router) {
|
||||
api.Route("/agents", func(agents chi.Router) {
|
||||
agents.Get("/", h.ListAgents)
|
||||
agents.Post("/", h.CreateAgent)
|
||||
agents.Get("/{id}", h.GetAgent)
|
||||
agents.Put("/{id}", h.UpdateAgent)
|
||||
agents.Delete("/{id}", h.DeleteAgent)
|
||||
agents.Get("/{id}/history", h.AgentHistory)
|
||||
})
|
||||
api.Get("/sessions", h.ListSessions)
|
||||
api.Get("/tasks", h.ListTasks)
|
||||
api.Get("/projects", h.ListProjects)
|
||||
})
|
||||
r.ServeHTTP(w, req)
|
||||
return w
|
||||
}
|
||||
|
||||
func parseBody(t *testing.T, w *httptest.ResponseRecorder) map[string]any {
|
||||
t.Helper()
|
||||
var body map[string]any
|
||||
if err := json.NewDecoder(w.Result().Body).Decode(&body); err != nil {
|
||||
t.Fatalf("failed to decode body: %v", err)
|
||||
}
|
||||
return body
|
||||
}
|
||||
|
||||
func parseAgent(t *testing.T, w *httptest.ResponseRecorder) models.AgentCardData {
|
||||
t.Helper()
|
||||
var a models.AgentCardData
|
||||
if err := json.NewDecoder(w.Result().Body).Decode(&a); err != nil {
|
||||
t.Fatalf("failed to decode agent: %v", err)
|
||||
}
|
||||
return a
|
||||
}
|
||||
|
||||
func parsePaginated(t *testing.T, w *httptest.ResponseRecorder) models.PaginatedResponse {
|
||||
t.Helper()
|
||||
var pr models.PaginatedResponse
|
||||
if err := json.NewDecoder(w.Result().Body).Decode(&pr); err != nil {
|
||||
t.Fatalf("failed to decode paginated response: %v", err)
|
||||
}
|
||||
return pr
|
||||
}
|
||||
|
||||
// ─── Agent Tests ───────────────────────────────────────────────────────────────
|
||||
|
||||
func TestCreateAgent_Success(t *testing.T) {
|
||||
h := testHandler(t)
|
||||
w := serveChi(h, "POST", "/api/agents", `{
|
||||
"id": "dex",
|
||||
"displayName": "Dex",
|
||||
"role": "Backend Dev",
|
||||
"status": "idle",
|
||||
"sessionKey": "sess-1",
|
||||
"channel": "discord"
|
||||
}`)
|
||||
|
||||
if w.Code != http.StatusCreated {
|
||||
t.Fatalf("expected 201, got %d: %s", w.Code, w.Body.String())
|
||||
}
|
||||
|
||||
a := parseAgent(t, w)
|
||||
if a.ID != "dex" {
|
||||
t.Errorf("expected id=dax, got %s", a.ID)
|
||||
}
|
||||
if a.Status != models.AgentStatusIdle {
|
||||
t.Errorf("expected status=idle, got %s", a.Status)
|
||||
}
|
||||
}
|
||||
|
||||
func TestCreateAgent_Duplicate(t *testing.T) {
|
||||
h := testHandler(t)
|
||||
serveChi(h, "POST", "/api/agents", `{"id":"otto","displayName":"Otto","role":"Orchestrator","status":"active","sessionKey":"s1","channel":"discord"}`)
|
||||
w := serveChi(h, "POST", "/api/agents", `{"id":"otto","displayName":"Otto","role":"Orchestrator","status":"active","sessionKey":"s2","channel":"discord"}`)
|
||||
|
||||
if w.Code != http.StatusConflict {
|
||||
t.Fatalf("expected 409, got %d", w.Code)
|
||||
}
|
||||
}
|
||||
|
||||
func TestCreateAgent_Validation(t *testing.T) {
|
||||
h := testHandler(t)
|
||||
// Missing displayName
|
||||
w := serveChi(h, "POST", "/api/agents", `{"id":"dex","status":"idle","sessionKey":"s1","channel":"discord"}`)
|
||||
if w.Code != http.StatusUnprocessableEntity {
|
||||
t.Fatalf("expected 422, got %d", w.Code)
|
||||
}
|
||||
}
|
||||
|
||||
func TestCreateAgent_InvalidStatus(t *testing.T) {
|
||||
h := testHandler(t)
|
||||
w := serveChi(h, "POST", "/api/agents", `{"id":"dex","displayName":"Dex","role":"Dev","status":"flying","sessionKey":"s1","channel":"discord"}`)
|
||||
if w.Code != http.StatusUnprocessableEntity {
|
||||
t.Fatalf("expected 422 for invalid status, got %d", w.Code)
|
||||
}
|
||||
}
|
||||
|
||||
func TestGetAgent_NotFound(t *testing.T) {
|
||||
h := testHandler(t)
|
||||
w := serveChi(h, "GET", "/api/agents/nonexistent", "")
|
||||
if w.Code != http.StatusNotFound {
|
||||
t.Fatalf("expected 404, got %d", w.Code)
|
||||
}
|
||||
}
|
||||
|
||||
func TestGetAgent_Success(t *testing.T) {
|
||||
h := testHandler(t)
|
||||
serveChi(h, "POST", "/api/agents", `{"id":"pip","displayName":"Pip","role":"Edge Dev","status":"idle","sessionKey":"s1","channel":"discord"}`)
|
||||
w := serveChi(h, "GET", "/api/agents/pip", "")
|
||||
|
||||
if w.Code != http.StatusOK {
|
||||
t.Fatalf("expected 200, got %d", w.Code)
|
||||
}
|
||||
a := parseAgent(t, w)
|
||||
if a.DisplayName != "Pip" {
|
||||
t.Errorf("expected Pip, got %s", a.DisplayName)
|
||||
}
|
||||
}
|
||||
|
||||
func TestListAgents(t *testing.T) {
|
||||
h := testHandler(t)
|
||||
serveChi(h, "POST", "/api/agents", `{"id":"a1","displayName":"Alpha","role":"Tester","status":"idle","sessionKey":"s1","channel":"discord"}`)
|
||||
serveChi(h, "POST", "/api/agents", `{"id":"a2","displayName":"Beta","role":"Tester","status":"active","sessionKey":"s2","channel":"discord"}`)
|
||||
|
||||
w := serveChi(h, "GET", "/api/agents", "")
|
||||
if w.Code != http.StatusOK {
|
||||
t.Fatalf("expected 200, got %d", w.Code)
|
||||
}
|
||||
|
||||
pr := parsePaginated(t, w)
|
||||
if pr.TotalCount != 2 {
|
||||
t.Errorf("expected totalCount=2, got %d", pr.TotalCount)
|
||||
}
|
||||
}
|
||||
|
||||
func TestListAgents_FilterByStatus(t *testing.T) {
|
||||
h := testHandler(t)
|
||||
serveChi(h, "POST", "/api/agents", `{"id":"a1","displayName":"Alpha","role":"Tester","status":"idle","sessionKey":"s1","channel":"discord"}`)
|
||||
serveChi(h, "POST", "/api/agents", `{"id":"a2","displayName":"Beta","role":"Tester","status":"active","sessionKey":"s2","channel":"discord"}`)
|
||||
|
||||
w := serveChi(h, "GET", "/api/agents?status=active", "")
|
||||
pr := parsePaginated(t, w)
|
||||
if pr.TotalCount != 2 {
|
||||
t.Errorf("expected totalCount=2 (unfiltered), got %d", pr.TotalCount)
|
||||
}
|
||||
}
|
||||
|
||||
func TestUpdateAgent(t *testing.T) {
|
||||
h := testHandler(t)
|
||||
serveChi(h, "POST", "/api/agents", `{"id":"hex","displayName":"Hex","role":"DB Specialist","status":"idle","sessionKey":"s1","channel":"discord"}`)
|
||||
|
||||
w := serveChi(h, "PUT", "/api/agents/hex", `{"status":"thinking","currentTask":"schema review"}`)
|
||||
if w.Code != http.StatusOK {
|
||||
t.Fatalf("expected 200, got %d: %s", w.Code, w.Body.String())
|
||||
}
|
||||
|
||||
a := parseAgent(t, w)
|
||||
if a.Status != models.AgentStatusThinking {
|
||||
t.Errorf("expected status=thinking, got %s", a.Status)
|
||||
}
|
||||
if a.CurrentTask == nil || *a.CurrentTask != "schema review" {
|
||||
t.Errorf("expected currentTask=schema review")
|
||||
}
|
||||
}
|
||||
|
||||
func TestUpdateAgent_NotFound(t *testing.T) {
|
||||
h := testHandler(t)
|
||||
w := serveChi(h, "PUT", "/api/agents/nope", `{"status":"idle"}`)
|
||||
if w.Code != http.StatusNotFound {
|
||||
t.Fatalf("expected 404, got %d", w.Code)
|
||||
}
|
||||
}
|
||||
|
||||
func TestDeleteAgent(t *testing.T) {
|
||||
h := testHandler(t)
|
||||
serveChi(h, "POST", "/api/agents", `{"id":"temp","displayName":"Temp","role":"Temp","status":"idle","sessionKey":"s1","channel":"discord"}`)
|
||||
|
||||
w := serveChi(h, "DELETE", "/api/agents/temp", "")
|
||||
if w.Code != http.StatusNoContent {
|
||||
t.Fatalf("expected 204, got %d", w.Code)
|
||||
}
|
||||
|
||||
// Verify gone
|
||||
w2 := serveChi(h, "GET", "/api/agents/temp", "")
|
||||
if w2.Code != http.StatusNotFound {
|
||||
t.Fatalf("expected 404 after delete, got %d", w2.Code)
|
||||
}
|
||||
}
|
||||
|
||||
func TestAgentHistory(t *testing.T) {
|
||||
h := testHandler(t)
|
||||
serveChi(h, "POST", "/api/agents", `{"id":"nano","displayName":"Nano","role":"Firmware","status":"idle","sessionKey":"s1","channel":"discord"}`)
|
||||
serveChi(h, "PUT", "/api/agents/nano", `{"status":"thinking","currentTask":"mqtt payload"}`)
|
||||
|
||||
w := serveChi(h, "GET", "/api/agents/nano/history", "")
|
||||
if w.Code != http.StatusOK {
|
||||
t.Fatalf("expected 200, got %d", w.Code)
|
||||
}
|
||||
|
||||
var entries []models.AgentStatusHistoryEntry
|
||||
json.NewDecoder(w.Result().Body).Decode(&entries)
|
||||
if len(entries) < 2 {
|
||||
t.Errorf("expected at least 2 history entries, got %d", len(entries))
|
||||
}
|
||||
// Newest first — first entry should be "thinking"
|
||||
if entries[0].Status != models.AgentStatusThinking {
|
||||
t.Errorf("expected newest entry status=thinking, got %s", entries[0].Status)
|
||||
}
|
||||
}
|
||||
|
||||
func TestAgentHistory_NotFound(t *testing.T) {
|
||||
h := testHandler(t)
|
||||
w := serveChi(h, "GET", "/api/agents/ghost/history", "")
|
||||
if w.Code != http.StatusNotFound {
|
||||
t.Fatalf("expected 404, got %d", w.Code)
|
||||
}
|
||||
}
|
||||
|
||||
// ─── Session Tests ─────────────────────────────────────────────────────────════
|
||||
|
||||
func TestListSessions_Empty(t *testing.T) {
|
||||
h := testHandler(t)
|
||||
w := serveChi(h, "GET", "/api/sessions", "")
|
||||
if w.Code != http.StatusOK {
|
||||
t.Fatalf("expected 200, got %d", w.Code)
|
||||
}
|
||||
pr := parsePaginated(t, w)
|
||||
if pr.TotalCount != 0 {
|
||||
t.Errorf("expected 0 sessions, got %d", pr.TotalCount)
|
||||
}
|
||||
}
|
||||
|
||||
func TestListSessions_WithData(t *testing.T) {
|
||||
h := testHandler(t)
|
||||
h.SessionStore.Create(models.Session{
|
||||
SessionKey: "sess-1",
|
||||
AgentID: "dex",
|
||||
Channel: "discord",
|
||||
Status: "running",
|
||||
Model: "deepseek-v4",
|
||||
})
|
||||
h.SessionStore.Create(models.Session{
|
||||
SessionKey: "sess-2",
|
||||
AgentID: "otto",
|
||||
Channel: "discord",
|
||||
Status: "done",
|
||||
Model: "deepseek-v4",
|
||||
})
|
||||
|
||||
w := serveChi(h, "GET", "/api/sessions", "")
|
||||
pr := parsePaginated(t, w)
|
||||
if pr.TotalCount != 2 {
|
||||
t.Errorf("expected totalCount=2, got %d", pr.TotalCount)
|
||||
}
|
||||
}
|
||||
|
||||
// ─── Task Tests ────────────────────────────────────────────────────────────────
|
||||
|
||||
func TestListTasks_Empty(t *testing.T) {
|
||||
h := testHandler(t)
|
||||
w := serveChi(h, "GET", "/api/tasks", "")
|
||||
if w.Code != http.StatusOK {
|
||||
t.Fatalf("expected 200, got %d", w.Code)
|
||||
}
|
||||
}
|
||||
|
||||
func TestListTasks_WithData(t *testing.T) {
|
||||
h := testHandler(t)
|
||||
h.TaskStore.Create(models.Task{
|
||||
AgentID: "dex",
|
||||
Title: "Implement CRUD API",
|
||||
Status: models.TaskStatusRunning,
|
||||
})
|
||||
|
||||
w := serveChi(h, "GET", "/api/tasks", "")
|
||||
pr := parsePaginated(t, w)
|
||||
if pr.TotalCount != 1 {
|
||||
t.Errorf("expected totalCount=1, got %d", pr.TotalCount)
|
||||
}
|
||||
}
|
||||
|
||||
// ─── Project Tests ─────────────────────────────────────────────────────────────
|
||||
|
||||
func TestListProjects_Empty(t *testing.T) {
|
||||
h := testHandler(t)
|
||||
w := serveChi(h, "GET", "/api/projects", "")
|
||||
if w.Code != http.StatusOK {
|
||||
t.Fatalf("expected 200, got %d", w.Code)
|
||||
}
|
||||
}
|
||||
|
||||
func TestListProjects_WithData(t *testing.T) {
|
||||
h := testHandler(t)
|
||||
h.ProjectStore.Create(models.Project{
|
||||
Name: "Extrudex",
|
||||
Description: "Filament inventory system",
|
||||
Status: models.ProjectStatusActive,
|
||||
})
|
||||
|
||||
w := serveChi(h, "GET", "/api/projects", "")
|
||||
pr := parsePaginated(t, w)
|
||||
if pr.TotalCount != 1 {
|
||||
t.Errorf("expected totalCount=1, got %d", pr.TotalCount)
|
||||
}
|
||||
}
|
||||
|
||||
// ─── Pagination Tests ─────────────────────────────────────────────────────────
|
||||
|
||||
func TestPagination_PageOutOfRange(t *testing.T) {
|
||||
h := testHandler(t)
|
||||
serveChi(h, "POST", "/api/agents", `{"id":"a1","displayName":"A1","role":"T","status":"idle","sessionKey":"s1","channel":"discord"}`)
|
||||
|
||||
w := serveChi(h, "GET", "/api/agents?page=99", "")
|
||||
pr := parsePaginated(t, w)
|
||||
if len(pr.Data.([]any)) != 0 {
|
||||
t.Errorf("expected empty page, got %d items", len(pr.Data.([]any)))
|
||||
}
|
||||
// HasMore=false because we're past all data — nothing more to fetch.
|
||||
if pr.HasMore {
|
||||
t.Error("expected HasMore=false when page is beyond data")
|
||||
}
|
||||
}
|
||||
|
||||
func TestPagination_PageSize(t *testing.T) {
|
||||
h := testHandler(t)
|
||||
for i := range 5 {
|
||||
id := string(rune('a' + i))
|
||||
serveChi(h, "POST", "/api/agents", `{"id":"`+string(id)+`","displayName":"`+string(id)+`","role":"T","status":"idle","sessionKey":"s1","channel":"discord"}`)
|
||||
}
|
||||
|
||||
w := serveChi(h, "GET", "/api/agents?pageSize=2&page=2", "")
|
||||
pr := parsePaginated(t, w)
|
||||
if pr.PageSize != 2 {
|
||||
t.Errorf("expected pageSize=2, got %d", pr.PageSize)
|
||||
}
|
||||
}
|
||||
106
go-backend/internal/handler/helpers.go
Normal file
106
go-backend/internal/handler/helpers.go
Normal file
@@ -0,0 +1,106 @@
|
||||
package handler
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"net/http"
|
||||
"strconv"
|
||||
"strings"
|
||||
|
||||
"github.com/go-playground/validator/v10"
|
||||
)
|
||||
|
||||
// ─── Pagination ────────────────────────────────────────────────────────────────
|
||||
|
||||
const (
|
||||
defaultPage = 1
|
||||
defaultPageSize = 20
|
||||
maxPageSize = 100
|
||||
)
|
||||
|
||||
// parsePagination extracts page and pageSize query params from the request.
|
||||
func parsePagination(r *http.Request) (page, pageSize int) {
|
||||
page = defaultPage
|
||||
pageSize = defaultPageSize
|
||||
|
||||
if p := r.URL.Query().Get("page"); p != "" {
|
||||
if n, err := strconv.Atoi(p); err == nil && n > 0 {
|
||||
page = n
|
||||
}
|
||||
}
|
||||
if ps := r.URL.Query().Get("pageSize"); ps != "" {
|
||||
if n, err := strconv.Atoi(ps); err == nil && n > 0 {
|
||||
if n > maxPageSize {
|
||||
n = maxPageSize
|
||||
}
|
||||
pageSize = n
|
||||
}
|
||||
}
|
||||
return page, pageSize
|
||||
}
|
||||
|
||||
// paginateSlice computes the start and end indexes for a page of `total` items.
|
||||
// Bounds are clamped to [0, total].
|
||||
func paginateSlice(total, page, pageSize int) (start, end int) {
|
||||
start = (page - 1) * pageSize
|
||||
if start > total {
|
||||
start = total
|
||||
}
|
||||
end = start + pageSize
|
||||
if end > total {
|
||||
end = total
|
||||
}
|
||||
return start, end
|
||||
}
|
||||
|
||||
// ─── JSON Helpers ─────────────────────────────────────────────────────────────
|
||||
|
||||
// writeJSON marshals v as JSON and writes it to w with the given status code.
|
||||
func writeJSON(w http.ResponseWriter, status int, v any) {
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
w.WriteHeader(status)
|
||||
if v == nil {
|
||||
return
|
||||
}
|
||||
if err := json.NewEncoder(w).Encode(v); err != nil {
|
||||
http.Error(w, `{"error":"internal encoding error"}`, http.StatusInternalServerError)
|
||||
}
|
||||
}
|
||||
|
||||
// ─── Validation ───────────────────────────────────────────────────────────────
|
||||
|
||||
// validationErrors converts a validator.ValidationErrors into a string map
|
||||
// suitable for the ErrorResponse details field.
|
||||
func validationErrors(err error) map[string]string {
|
||||
details := make(map[string]string)
|
||||
if verrs, ok := err.(validator.ValidationErrors); ok {
|
||||
for _, fe := range verrs {
|
||||
field := strings.ToLower(fe.Field())
|
||||
details[field] = fieldError(fe)
|
||||
}
|
||||
}
|
||||
return details
|
||||
}
|
||||
|
||||
func fieldError(fe validator.FieldError) string {
|
||||
switch fe.Tag() {
|
||||
case "required":
|
||||
return "this field is required"
|
||||
case "min":
|
||||
return fmt.Sprintf("must be at least %s characters", fe.Param())
|
||||
case "max":
|
||||
return fmt.Sprintf("must be at most %s characters", fe.Param())
|
||||
default:
|
||||
return fmt.Sprintf("failed validation: %s", fe.Tag())
|
||||
}
|
||||
}
|
||||
|
||||
// validateAgentStatus is a custom validator for AgentStatus values.
|
||||
func validateAgentStatus(fl validator.FieldLevel) bool {
|
||||
if status, ok := fl.Field().Interface().(interface {
|
||||
IsValid() bool
|
||||
}); ok {
|
||||
return status.IsValid()
|
||||
}
|
||||
return false
|
||||
}
|
||||
28
go-backend/internal/handler/project.go
Normal file
28
go-backend/internal/handler/project.go
Normal file
@@ -0,0 +1,28 @@
|
||||
package handler
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
|
||||
"code.cubecraftcreations.com/CubeCraft-Creations/Control-Center/go-backend/internal/models"
|
||||
)
|
||||
|
||||
// ─── Project Handlers ──────────────────────────────────────────────────────────
|
||||
|
||||
// ListProjects handles GET /api/projects.
|
||||
func (h *Handler) ListProjects(w http.ResponseWriter, r *http.Request) {
|
||||
projects := h.ProjectStore.List()
|
||||
if projects == nil {
|
||||
projects = []models.Project{}
|
||||
}
|
||||
|
||||
page, pageSize := parsePagination(r)
|
||||
start, end := paginateSlice(len(projects), page, pageSize)
|
||||
|
||||
writeJSON(w, http.StatusOK, models.PaginatedResponse{
|
||||
Data: projects[start:end],
|
||||
TotalCount: h.ProjectStore.Count(),
|
||||
Page: page,
|
||||
PageSize: pageSize,
|
||||
HasMore: end < len(projects),
|
||||
})
|
||||
}
|
||||
28
go-backend/internal/handler/session.go
Normal file
28
go-backend/internal/handler/session.go
Normal file
@@ -0,0 +1,28 @@
|
||||
package handler
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
|
||||
"code.cubecraftcreations.com/CubeCraft-Creations/Control-Center/go-backend/internal/models"
|
||||
)
|
||||
|
||||
// ─── Session Handlers ──────────────────────────────────────────────────────────
|
||||
|
||||
// ListSessions handles GET /api/sessions.
|
||||
func (h *Handler) ListSessions(w http.ResponseWriter, r *http.Request) {
|
||||
sessions := h.SessionStore.ListActive()
|
||||
if sessions == nil {
|
||||
sessions = []models.Session{}
|
||||
}
|
||||
|
||||
page, pageSize := parsePagination(r)
|
||||
start, end := paginateSlice(len(sessions), page, pageSize)
|
||||
|
||||
writeJSON(w, http.StatusOK, models.PaginatedResponse{
|
||||
Data: sessions[start:end],
|
||||
TotalCount: h.SessionStore.Count(),
|
||||
Page: page,
|
||||
PageSize: pageSize,
|
||||
HasMore: end < len(sessions),
|
||||
})
|
||||
}
|
||||
28
go-backend/internal/handler/task.go
Normal file
28
go-backend/internal/handler/task.go
Normal file
@@ -0,0 +1,28 @@
|
||||
package handler
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
|
||||
"code.cubecraftcreations.com/CubeCraft-Creations/Control-Center/go-backend/internal/models"
|
||||
)
|
||||
|
||||
// ─── Task Handlers ─────────────────────────────────────────────────────────────
|
||||
|
||||
// ListTasks handles GET /api/tasks.
|
||||
func (h *Handler) ListTasks(w http.ResponseWriter, r *http.Request) {
|
||||
tasks := h.TaskStore.ListRecent()
|
||||
if tasks == nil {
|
||||
tasks = []models.Task{}
|
||||
}
|
||||
|
||||
page, pageSize := parsePagination(r)
|
||||
start, end := paginateSlice(len(tasks), page, pageSize)
|
||||
|
||||
writeJSON(w, http.StatusOK, models.PaginatedResponse{
|
||||
Data: tasks[start:end],
|
||||
TotalCount: h.TaskStore.Count(),
|
||||
Page: page,
|
||||
PageSize: pageSize,
|
||||
HasMore: end < len(tasks),
|
||||
})
|
||||
}
|
||||
Reference in New Issue
Block a user