65 lines
1.5 KiB
Go
65 lines
1.5 KiB
Go
package httpapi
|
|
|
|
import (
|
|
"net/http"
|
|
|
|
"watch-party-backend/internal/repo"
|
|
"watch-party-backend/internal/service"
|
|
|
|
"github.com/gin-gonic/gin"
|
|
)
|
|
|
|
func NewRouter(svc service.EpisodeService) *gin.Engine {
|
|
r := gin.New()
|
|
r.Use(gin.Logger(), gin.Recovery())
|
|
|
|
r.GET("/healthz", func(c *gin.Context) {
|
|
c.JSON(http.StatusOK, gin.H{"status": "ok"})
|
|
})
|
|
|
|
v1 := r.Group("/v1")
|
|
|
|
v1.GET("/current", func(c *gin.Context) {
|
|
cur, err := svc.GetCurrent(c.Request.Context())
|
|
if err != nil {
|
|
if err == repo.ErrNotFound {
|
|
c.JSON(http.StatusNotFound, gin.H{"error": "no current row found"})
|
|
return
|
|
}
|
|
c.JSON(http.StatusInternalServerError, gin.H{"error": "query failed"})
|
|
return
|
|
}
|
|
c.JSON(http.StatusOK, cur)
|
|
})
|
|
|
|
type setCurrentReq struct {
|
|
ID int64 `json:"id" binding:"required"`
|
|
StartTime string `json:"start_time" binding:"required"`
|
|
}
|
|
|
|
v1.POST("/current", func(c *gin.Context) {
|
|
var req setCurrentReq
|
|
if err := c.ShouldBindJSON(&req); err != nil {
|
|
c.JSON(http.StatusBadRequest, gin.H{"error": "invalid payload"})
|
|
return
|
|
}
|
|
cur, err := svc.SetCurrent(c.Request.Context(), req.ID, req.StartTime)
|
|
if err != nil {
|
|
switch err {
|
|
case service.ErrInvalidTime:
|
|
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
|
|
return
|
|
case repo.ErrNotFound:
|
|
c.JSON(http.StatusNotFound, gin.H{"error": "id not found"})
|
|
return
|
|
default:
|
|
c.JSON(http.StatusInternalServerError, gin.H{"error": "update failed"})
|
|
return
|
|
}
|
|
}
|
|
c.JSON(http.StatusOK, cur)
|
|
})
|
|
|
|
return r
|
|
}
|