Files
digital-psychology/apps/api/internal/handler/scale.go
T
jackyu66gitandCursor 15a9db374a feat: add exploration scale list, questions, and scoring
Seed communication-style scale, expose /api/v1/scales APIs, and wire
Explore/Scale H5 pages for the P1 探索测试 path.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-08-02 16:29:31 +08:00

75 lines
2.0 KiB
Go

package handler
import (
"net/http"
"github.com/gin-gonic/gin"
"github.com/google/uuid"
"github.com/yuxingu/digital-psychology/apps/api/internal/middleware"
"github.com/yuxingu/digital-psychology/apps/api/internal/service/scale"
"github.com/yuxingu/digital-psychology/apps/api/pkg/response"
)
// ScaleHandler exposes 探索测试 APIs.
type ScaleHandler struct {
Svc *scale.Service
}
// Register mounts routes.
func (h *ScaleHandler) Register(rg *gin.RouterGroup) {
rg.GET("/scales", h.List)
rg.GET("/scales/:slug", h.Get)
rg.POST("/scales/:slug/result", h.Submit)
}
// List handles GET /scales.
func (h *ScaleHandler) List(c *gin.Context) {
items, err := h.Svc.List(c.Request.Context())
if err != nil {
response.Fail(c, http.StatusInternalServerError, 50003, "list failed")
return
}
response.OK(c, gin.H{"items": items})
}
// Get handles GET /scales/:slug.
func (h *ScaleHandler) Get(c *gin.Context) {
d, err := h.Svc.Get(c.Request.Context(), c.Param("slug"))
if err != nil {
response.Fail(c, http.StatusNotFound, 40402, err.Error())
return
}
response.OK(c, d)
}
// Submit handles POST /scales/:slug/result.
func (h *ScaleHandler) Submit(c *gin.Context) {
userID, ok := middleware.UserIDFromContext(c)
if !ok {
response.Fail(c, http.StatusUnauthorized, 40100, "unauthorized")
return
}
var req struct {
ProfileID string `json:"profile_id" binding:"required"`
Answers map[string]string `json:"answers" binding:"required"`
}
if err := c.ShouldBindJSON(&req); err != nil {
response.Fail(c, http.StatusBadRequest, 10000, "invalid request")
return
}
pid, err := uuid.Parse(req.ProfileID)
if err != nil {
response.Fail(c, http.StatusBadRequest, 10000, "invalid profile_id")
return
}
out, err := h.Svc.Submit(c.Request.Context(), userID, c.Param("slug"), scale.SubmitInput{
ProfileID: pid, Answers: req.Answers,
})
if err != nil {
response.Fail(c, http.StatusBadRequest, 30006, err.Error())
return
}
response.OK(c, out)
}