server/qa/api/exercice.go

82 lines
2.0 KiB
Go
Raw Normal View History

package api
import (
2022-11-06 15:36:31 +00:00
"fmt"
"log"
"net/http"
"strconv"
adminapi "srs.epita.fr/fic-server/admin/api"
"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 declareExercicesRoutes(router *gin.RouterGroup) {
router.GET("/exercices", listExercices)
2022-11-06 15:36:31 +00:00
exercicesRoutes := router.Group("/exercices/:eid")
exercicesRoutes.Use(exerciceHandler)
exercicesRoutes.GET("", showExercice)
2022-11-07 00:00:04 +00:00
declareQARoutes(exercicesRoutes)
}
2022-11-06 15:36:31 +00:00
func exerciceHandler(c *gin.Context) {
var exercice *fic.Exercice
if eid, err := strconv.ParseInt(string(c.Param("eid")), 10, 64); err != nil {
c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"errmsg": "Bad exercice identifier."})
return
} else if exercice, err = fic.GetExercice(eid); err != nil {
c.AbortWithStatusJSON(http.StatusNotFound, gin.H{"errmsg": "Exercice not found."})
return
}
if th, ok := c.Get("theme"); ok {
if exercice.IdTheme == nil || *exercice.IdTheme != th.(*fic.Theme).Id {
2022-11-06 15:36:31 +00:00
c.AbortWithStatusJSON(http.StatusNotFound, gin.H{"errmsg": "Exercice not found."})
return
}
}
2022-11-06 15:36:31 +00:00
c.Set("exercice", exercice)
c.Next()
}
2022-11-06 15:36:31 +00:00
func listExercices(c *gin.Context) {
2022-11-07 00:00:04 +00:00
var exercices []*fic.Exercice
var err error
if theme, ok := c.Get("theme"); ok {
exercices, err = theme.(*fic.Theme).GetExercices()
} else {
// List all exercices
exercices, err = fic.GetExercices()
}
2022-11-06 15:36:31 +00:00
if err != nil {
log.Println("Unable to GetExercices: ", err.Error())
c.AbortWithStatusJSON(http.StatusInternalServerError, gin.H{"errmsg": fmt.Sprintf("Unable to list exercices: %s", err.Error())})
return
}
c.JSON(http.StatusOK, exercices)
}
2022-11-06 15:36:31 +00:00
func showExercice(c *gin.Context) {
2023-11-25 12:43:41 +00:00
if adminLink == "" {
c.JSON(http.StatusOK, c.MustGet("exercice"))
return
}
var e adminapi.Exercice
err := fwdAdmin(c.Request.Method, fmt.Sprintf("/api/exercices/%s", string(c.Param("eid"))), nil, &e)
if err != nil {
log.Println("Unable to make request to admin:", err.Error())
c.JSON(http.StatusOK, c.MustGet("exercice"))
return
}
c.JSON(http.StatusOK, e)
}