server/qa/api/theme.go

65 lines
1.5 KiB
Go
Raw Normal View History

package api
import (
2022-11-06 15:36:31 +00:00
"fmt"
"log"
"net/http"
"strconv"
"srs.epita.fr/fic-server/libfic"
2022-11-06 15:36:31 +00:00
"github.com/gin-gonic/gin"
)
2022-11-06 15:36:31 +00:00
func declareThemesRoutes(router *gin.RouterGroup) {
router.GET("/themes", listThemes)
router.GET("/themes.json", exportThemes)
2022-11-06 15:36:31 +00:00
themesRoutes := router.Group("/themes/:thid")
themesRoutes.Use(themeHandler)
themesRoutes.GET("", showTheme)
2022-11-06 15:36:31 +00:00
declareExercicesRoutes(themesRoutes)
}
2022-11-06 15:36:31 +00:00
func themeHandler(c *gin.Context) {
var theme *fic.Theme
if thid, err := strconv.ParseInt(string(c.Param("thid")), 10, 64); err != nil {
c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"errmsg": "Bad theme identifier."})
return
} else if theme, err = fic.GetTheme(thid); err != nil {
c.AbortWithStatusJSON(http.StatusNotFound, gin.H{"errmsg": "Theme not found."})
return
}
2022-11-06 15:36:31 +00:00
c.Set("theme", theme)
2022-11-06 15:36:31 +00:00
c.Next()
}
2022-11-06 15:36:31 +00:00
func listThemes(c *gin.Context) {
themes, err := fic.GetThemes()
if err != nil {
log.Println("Unable to GetThemes: ", err.Error())
c.AbortWithStatusJSON(http.StatusInternalServerError, gin.H{"errmsg": fmt.Sprintf("Unable to list themes: %s", err.Error())})
return
}
2022-11-06 15:36:31 +00:00
c.JSON(http.StatusOK, themes)
}
2022-11-06 15:36:31 +00:00
func exportThemes(c *gin.Context) {
themes, err := fic.ExportThemes()
if err != nil {
log.Println("Unable to ExportThemes: ", err.Error())
c.AbortWithStatusJSON(http.StatusInternalServerError, gin.H{"errmsg": fmt.Sprintf("Unable to export themes: %s", err.Error())})
return
}
c.JSON(http.StatusOK, themes)
}
2022-11-06 15:36:31 +00:00
func showTheme(c *gin.Context) {
c.JSON(http.StatusOK, c.MustGet("theme"))
}