97 lines
2.3 KiB
Go
97 lines
2.3 KiB
Go
package api
|
|
|
|
import (
|
|
"encoding/json"
|
|
"net/http"
|
|
"strconv"
|
|
"strings"
|
|
|
|
"github.com/fmartingr/ccrm/server/internal/db"
|
|
)
|
|
|
|
// SessionsHandler handles session-related API endpoints.
|
|
type SessionsHandler struct {
|
|
DB *db.DB
|
|
}
|
|
|
|
// List handles GET /api/sessions
|
|
func (h *SessionsHandler) List(w http.ResponseWriter, r *http.Request) {
|
|
activeOnly := r.URL.Query().Get("active") == "true"
|
|
|
|
sessions, err := h.DB.ListSessions(activeOnly)
|
|
if err != nil {
|
|
writeError(w, http.StatusInternalServerError, err.Error())
|
|
return
|
|
}
|
|
|
|
if sessions == nil {
|
|
sessions = []*db.Session{}
|
|
}
|
|
|
|
writeJSON(w, http.StatusOK, sessions)
|
|
}
|
|
|
|
// Get handles GET /api/sessions/{id}
|
|
func (h *SessionsHandler) Get(w http.ResponseWriter, r *http.Request) {
|
|
id := extractPathParam(r, "/api/sessions/")
|
|
if id == "" {
|
|
writeError(w, http.StatusBadRequest, "session ID required")
|
|
return
|
|
}
|
|
|
|
// Strip any trailing path segments (like /events)
|
|
if idx := strings.Index(id, "/"); idx >= 0 {
|
|
id = id[:idx]
|
|
}
|
|
|
|
session, err := h.DB.GetSession(id)
|
|
if err != nil {
|
|
writeError(w, http.StatusNotFound, "session not found")
|
|
return
|
|
}
|
|
|
|
writeJSON(w, http.StatusOK, session)
|
|
}
|
|
|
|
// ListEvents handles GET /api/sessions/{id}/events
|
|
func (h *SessionsHandler) ListEvents(w http.ResponseWriter, r *http.Request) {
|
|
// Extract session ID from path
|
|
path := strings.TrimPrefix(r.URL.Path, "/api/sessions/")
|
|
parts := strings.SplitN(path, "/", 2)
|
|
if len(parts) < 1 {
|
|
writeError(w, http.StatusBadRequest, "session ID required")
|
|
return
|
|
}
|
|
sessionID := parts[0]
|
|
|
|
limit, _ := strconv.Atoi(r.URL.Query().Get("limit"))
|
|
offset, _ := strconv.Atoi(r.URL.Query().Get("offset"))
|
|
|
|
events, err := h.DB.ListEvents(sessionID, limit, offset)
|
|
if err != nil {
|
|
writeError(w, http.StatusInternalServerError, err.Error())
|
|
return
|
|
}
|
|
|
|
if events == nil {
|
|
events = []*db.Event{}
|
|
}
|
|
|
|
writeJSON(w, http.StatusOK, events)
|
|
}
|
|
|
|
func extractPathParam(r *http.Request, prefix string) string {
|
|
return strings.TrimPrefix(r.URL.Path, prefix)
|
|
}
|
|
|
|
func writeJSON(w http.ResponseWriter, status int, data any) {
|
|
w.Header().Set("Content-Type", "application/json")
|
|
w.WriteHeader(status)
|
|
json.NewEncoder(w).Encode(data)
|
|
}
|
|
|
|
func writeError(w http.ResponseWriter, status int, msg string) {
|
|
w.Header().Set("Content-Type", "application/json")
|
|
w.WriteHeader(status)
|
|
json.NewEncoder(w).Encode(map[string]string{"error": msg})
|
|
}
|