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"
2019-06-03 09:32:43 +00:00
"github.com/animenotifier/notify.moe/arn"
2018-10-27 02:01:21 +00:00
)
// Ranking returns the ranking information for the character via the API.
2019-06-01 04:55:49 +00:00
func Ranking(ctx aero.Context) error {
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
2019-06-01 04:55:49 +00:00
ctx.Response().SetHeader("Access-Control-Allow-Origin", "*")
2018-10-27 02:06:36 +00:00
// 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
}