|
| 1 | +import { Controller, Get, Query } from '@nestjs/common'; |
| 2 | +import { InjectRepository } from '@nestjs/typeorm'; |
| 3 | +import { Repository } from 'typeorm'; |
| 4 | +import { UserEntity } from '../../database/entities/user.entity'; |
| 5 | +import { CacheService } from '../../cache/cache.service'; |
| 6 | + |
| 7 | +@Controller('leaderboard') |
| 8 | +export class LeaderboardController { |
| 9 | + constructor( |
| 10 | + @InjectRepository(UserEntity) |
| 11 | + private readonly userRepo: Repository<UserEntity>, |
| 12 | + private readonly cacheService: CacheService, |
| 13 | + ) {} |
| 14 | + |
| 15 | + @Get() |
| 16 | + async getLeaderboard( |
| 17 | + @Query('by') by: 'wins' | 'volume' | 'tickets' = 'wins', |
| 18 | + @Query('limit') limit: number = 50, |
| 19 | + ) { |
| 20 | + const cacheKey = `leaderboard:${by}:${limit}`; |
| 21 | + // Use generic leaderboard key for invalidation if needed, or specific one |
| 22 | + // Requirements said "leaderboard" key. |
| 23 | + |
| 24 | + return this.cacheService.wrap('leaderboard', 60, async () => { |
| 25 | + const query = this.userRepo.createQueryBuilder('user'); |
| 26 | + |
| 27 | + if (by === 'wins') { |
| 28 | + query.orderBy('user.totalRafflesWon', 'DESC'); |
| 29 | + } else if (by === 'volume') { |
| 30 | + query.orderBy('user.totalPrizeXlm', 'DESC'); |
| 31 | + } else if (by === 'tickets') { |
| 32 | + query.orderBy('user.totalTicketsBought', 'DESC'); |
| 33 | + } |
| 34 | + |
| 35 | + query.take(limit); |
| 36 | + |
| 37 | + const entries = await query.getMany(); |
| 38 | + return { entries }; |
| 39 | + }); |
| 40 | + } |
| 41 | +} |
0 commit comments