53 lines
1.1 KiB
Go
Raw Normal View History

2018-10-27 02:01:21 +00:00
package character
import (
"net/http"
"github.com/aerogo/aero"
"github.com/animenotifier/arn"
)
// Ranking returns the ranking information for the character via the API.
func Ranking(ctx *aero.Context) string {
2018-10-27 02:06:36 +00:00
// Check character ID
2018-10-27 02:01:21 +00:00
id := ctx.Get("id")
_, err := arn.GetCharacter(id)
if err != nil {
return ctx.Error(http.StatusNotFound, "Character not found", err)
}
2018-10-29 10:52:25 +00:00
// Create response object
response := struct {
Rank int `json:"rank"`
Percentile float64 `json:"percentile"`
}{}
2018-10-27 02:06:36 +00:00
// Sort characters
2018-10-27 02:01:21 +00:00
characters := arn.FilterCharacters(func(character *arn.Character) bool {
return !character.IsDraft
})
2018-10-29 10:52:25 +00:00
if len(characters) == 0 {
return ctx.JSON(response)
}
2018-10-27 02:01:21 +00:00
arn.SortCharactersByLikes(characters)
2018-10-27 02:06:36 +00:00
// Allow CORS
ctx.Response().Header().Set("Access-Control-Allow-Origin", "*")
// Return ranking
2018-10-27 02:01:21 +00:00
for index, character := range characters {
if character.ID == id {
2018-10-29 10:52:25 +00:00
response.Rank = index + 1
response.Percentile = float64(response.Rank) / float64(len(characters))
return ctx.JSON(response)
2018-10-27 02:01:21 +00:00
}
}
2018-10-27 02:06:36 +00:00
// If the ID wasn't found for some reason,
// return an empty string.
2018-10-29 10:52:25 +00:00
return ctx.JSON(response)
2018-10-27 02:01:21 +00:00
}