debug Popular bet
continuous-integration/drone/push Build is passing Details

pull/13/head
luevard 11 months ago
parent 74ddd915f9
commit a3aa69b07d

@ -21,4 +21,5 @@ interface BetDataSource {
fun getHistory(username: String): List<BetResultDetail>
fun getCurrent(username: String): List<BetDetail>
fun getMostPopularBet(): Bet?
fun updatePopularityScore(betId: String)
}

@ -168,4 +168,8 @@ class MockBetDataSource(private val mockData: MockDataSource.MockData) : BetData
override fun getMostPopularBet(): Bet? {
TODO("Not yet implemented")
}
override fun updatePopularityScore(betId: String) {
TODO("Not yet implemented")
}
}

@ -124,6 +124,21 @@ class PostgresBetDataSource(private val database: Database) : BetDataSource {
return null
}
override fun updatePopularityScore(betId: String) {
val bet = database.bets.filter { it.id eq betId }.firstOrNull()
if (bet == null) {
return
}
val participations = database.participations.filter { it.betId eq betId }
val stakes = participations.map { it.stake }
val score = (participations.count() * participations.count()) + stakes.sum()
database.update(BetsEntity) {
set(it.popularityscore, score)
where { it.id eq betId }
}
}
override fun addBet(bet: Bet) {
database.bets.add(
BetEntity {

@ -125,35 +125,6 @@ class PostgresDataSource : AllInDataSource() {
)
""".trimIndent()
)
database.execute("""
CREATE OR REPLACE FUNCTION update_popularity_score()
RETURNS TRIGGER AS ${'$'}${'$'}
DECLARE
participant_count INT;
total_stakes INT;
BEGIN
-- Calculate participant count and total stakes for the bet
SELECT COUNT(*), COALESCE(SUM(stake), 0) INTO participant_count, total_stakes
FROM participation
WHERE bet = NEW.bet;
-- Update the popularityscore in the bet table
UPDATE bet
SET popularityscore = (participant_count * participant_count + total_stakes)
WHERE id = NEW.bet;
RETURN NEW;
END;
${'$'}${'$'} LANGUAGE plpgsql;
DROP TRIGGER IF EXISTS update_popularity_score ON participation;
CREATE TRIGGER update_popularity_score
AFTER INSERT OR UPDATE ON participation
FOR EACH ROW
EXECUTE FUNCTION update_popularity_score();
""".trimIndent())
}
override val userDataSource: UserDataSource by lazy { PostgresUserDataSource(database) }

@ -22,6 +22,7 @@ fun Application.participationRouter() {
val userDataSource = this.dataSource.userDataSource
val participationDataSource = this.dataSource.participationDataSource
val betDataSource = this.dataSource.betDataSource
routing {
authenticate {
@ -59,6 +60,7 @@ fun Application.participationRouter() {
)
userDataSource.removeCoins(username = user.username, amount = participation.stake)
betDataSource.updatePopularityScore(participation.betId)
call.respond(HttpStatusCode.Created)
} else {
call.respond(HttpStatusCode.Forbidden, ApiMessage.NOT_ENOUGH_COINS)

Loading…
Cancel
Save