@@ -43,6 +43,7 @@ class RankingsService(
4343 private val mangaRanking = database.getCollection(Collections .MANGA_RANKING )
4444 private val peopleRanking = database.getCollection(Collections .PEOPLE_RANKING )
4545 private val characterRanking = database.getCollection(Collections .CHARACTER_RANKING )
46+ private val animeRankingTopTen = database.getCollection(Collections .ANIME_RANKING_TOP_TEN )
4647
4748 suspend fun getAnimeRanking (call : RoutingCall ) {
4849 val filter = call.request.queryParameters[" filter" ] ? : " airing"
@@ -327,4 +328,65 @@ class RankingsService(
327328 call.respond(HttpStatusCode .OK , Json .encodeToString(response))
328329 }
329330 }
331+
332+ suspend fun getAnimeTopTenRanking (call : RoutingCall ) {
333+ val filter = call.request.queryParameters[" filter" ] ? : " airing"
334+ val type = call.parameters[" type" ] ? : throw IllegalArgumentException (ErrorMessages .InvalidTopAnimeType .message)
335+
336+ if (parseAnimeType(type) == null ) call.respond(HttpStatusCode .BadRequest , ErrorResponse (ErrorMessages .InvalidTopAnimeType .message))
337+
338+ val timerKey = " ${Collections .ANIME_RANKING } _${Collections .TOP_TEN } _${type} _${filter} "
339+
340+ val needsUpdate = timers.needsUpdate(
341+ amount = 7 ,
342+ key = timerKey,
343+ unit = TimeUnit .DAY
344+ )
345+
346+ if (needsUpdate) {
347+ animeRankingTopTen.deleteMany(
348+ Filters .and (
349+ Filters .eq(" type" , type),
350+ Filters .eq(" subtype" , filter)
351+ )
352+ )
353+
354+ val params = mutableListOf<String >()
355+ params.add(" type=$type " )
356+ params.add(" filter=$filter " )
357+
358+ val response = RestClient .request(
359+ BaseUrls .JIKAN + Endpoints .TOP_ANIME + " ?${params.joinToString(" &" )} " ,
360+ AnimeSearch .serializer()
361+ ).data?.map { anime ->
362+ anime.toAnimeTopEntity(
363+ page = 0 ,
364+ top = " anime" ,
365+ type = type,
366+ subType = filter
367+ )
368+ }.orEmpty().take(11 ).distinctBy { it.malId }
369+
370+ val documentsToInsert = parseDataToDocuments(response, AnimeTopEntity .serializer())
371+ if (documentsToInsert.isNotEmpty()) animeRankingTopTen .insertMany(documentsToInsert)
372+ timers.update(timerKey)
373+
374+ val elements = documentsToInsert.map { documentToAnimeTopEntity(it) }
375+
376+ call.respond(HttpStatusCode .OK , Json .encodeToString(elements))
377+ } else {
378+ val animes = animeRankingTopTen
379+ .find(
380+ Filters .and (
381+ Filters .eq(" type" , type),
382+ Filters .eq(" subtype" , filter)
383+ )
384+ )
385+ .toList()
386+
387+ val elements = animes.map { documentToAnimeTopEntity(it) }
388+
389+ call.respond(HttpStatusCode .OK , Json .encodeToString(elements))
390+ }
391+ }
330392}
0 commit comments