package handler import ( "github.com/gin-gonic/gin" "net/http" "pcgamedb/crawler" "pcgamedb/db" "pcgamedb/model" ) type GetPopularGamesResponse struct { Status string `json:"status"` Message string `json:"message,omitempty"` Games []*model.GameInfo `json:"games"` } // GetPopularGameInfosHandler Get popular games // @Summary Get popular games // @Description Get popular games based on a specified type // @Tags popular // @Accept json // @Produce json // @Param type path string true "Type(igdb-most-visited, igdb-most-wanted-to-play, igdb-most-playing, igdb-most-played, steam-top, steam-week-top, steam-best-of-the-year, steam-most-played)" // @Success 200 {object} GetPopularGamesResponse // @Failure 400 {object} GetPopularGamesResponse // @Failure 500 {object} GetPopularGamesResponse // @Router /popular/{type} [get] func GetPopularGameInfosHandler(c *gin.Context) { rankingType, exist := c.Params.Get("type") if !exist { c.JSON(http.StatusBadRequest, GetPopularGamesResponse{ Status: "error", Message: "Missing ranking type", }) } popularityType := 0 var steam250Func func() ([]*model.GameInfo, error) = nil switch rankingType { case "igdb-most-visited": popularityType = 1 case "igdb-most-wanted-to-play": popularityType = 2 case "igdb-most-playing": popularityType = 3 case "igdb-most-played": popularityType = 4 case "steam-top": steam250Func = crawler.GetSteam250Top250 case "steam-week-top": steam250Func = crawler.GetSteam250WeekTop50 case "steam-best-of-the-year": steam250Func = crawler.GetSteam250BestOfTheYear case "steam-most-played": steam250Func = crawler.GetSteam250MostPlayed default: c.JSON(http.StatusBadRequest, GetPopularGamesResponse{ Status: "error", Message: "Invalid ranking type", }) } var infos []*model.GameInfo var err error if steam250Func != nil { infos, err = steam250Func() if err != nil { c.JSON(http.StatusInternalServerError, GetPopularGamesResponse{ Status: "error", Message: err.Error(), }) } if len(infos) > 10 { infos = infos[:10] } } else { offset := 0 for len(infos) < 10 { ids, err := crawler.GetIGDBPopularGameIDs(popularityType, offset, 20) if err != nil { c.JSON(http.StatusInternalServerError, GetPopularGamesResponse{ Status: "error", Message: err.Error(), }) } offset += 20 pids := make([]int, 20) for _, id := range ids { pid, err := crawler.GetIGDBAppParentCache(id) if err != nil { continue } pids = append(pids, pid) } newInfos, err := db.GetGameInfosByPlatformIDs("igdb", pids) if err != nil { c.JSON(http.StatusInternalServerError, GetPopularGamesResponse{ Status: "error", Message: err.Error(), }) } infos = append(infos, newInfos...) } if len(infos) > 10 { infos = infos[:10] } } c.JSON(http.StatusOK, GetPopularGamesResponse{ Status: "ok", Games: infos, }) }