added some initial routes, ways to show overall stats, matches
This commit is contained in:
86
Sources/App/Controllers/StatsController.swift
Normal file
86
Sources/App/Controllers/StatsController.swift
Normal file
@@ -0,0 +1,86 @@
|
||||
import Fluent
|
||||
import Vapor
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
struct StatsController: RouteCollection {
|
||||
func boot(routes: RoutesBuilder) throws {
|
||||
let statsRoute = routes.grouped("api", "stats")
|
||||
|
||||
statsRoute.get("allMatches", use: index)
|
||||
statsRoute.get("totalWins", use: totalWins)
|
||||
statsRoute.get("totalLosses", use: totalLosses)
|
||||
statsRoute.get("overall", use: overall)
|
||||
|
||||
//beaconsRoute.get("overallStats", use: index)
|
||||
//beaconsRoute.post("", use: create)
|
||||
// beaconsRoute.delete(":beaconID", use: delete)
|
||||
|
||||
}
|
||||
|
||||
func index(req: Request) throws -> EventLoopFuture<[Match]> {
|
||||
return Match.query(on: req.db).all()
|
||||
}
|
||||
|
||||
|
||||
func totalWins(req: Request) throws -> EventLoopFuture<Int> {
|
||||
return Match.query(on: req.db)
|
||||
.filter(\.$win == true)
|
||||
.count()
|
||||
}
|
||||
|
||||
func totalLosses(req: Request) throws -> EventLoopFuture<Int> {
|
||||
return Match.query(on: req.db)
|
||||
.filter(\.$win == false)
|
||||
.count()
|
||||
}
|
||||
|
||||
|
||||
func overall(req: Request) throws -> EventLoopFuture<Stats> {
|
||||
let lossCount = Match.query(on: req.db)
|
||||
.filter(\.$win == false)
|
||||
.count()
|
||||
|
||||
|
||||
let winCount = Match.query(on: req.db)
|
||||
.filter(\.$win == true )
|
||||
.count()
|
||||
|
||||
|
||||
|
||||
let combined = winCount.and(lossCount)
|
||||
|
||||
return combined.map { (winCount, lossCount) -> (Stats) in
|
||||
|
||||
let ratio:Double = (Double(winCount) / Double(lossCount)).truncate(places: 2)
|
||||
|
||||
return Stats.init(winLoss: String(ratio), totalWins: winCount, totalLosses: lossCount)
|
||||
}
|
||||
|
||||
}
|
||||
//
|
||||
|
||||
// func create(req: Request) throws -> EventLoopFuture<Beacon> {
|
||||
// let newBeacon = try req.content.decode(Beacon.Create.self)
|
||||
// let beacon = Beacon(id: UUID(), ownerId: nil)
|
||||
// return beacon.save(on: req.db).map { beacon }
|
||||
// }
|
||||
//
|
||||
// func delete(req: Request) throws -> EventLoopFuture<HTTPStatus> {
|
||||
// return Beacon.find(req.parameters.get("beaconID"), on: req.db)
|
||||
// .unwrap(or: Abort(.notFound))
|
||||
// .flatMap { $0.delete(on: req.db) }
|
||||
// .transform(to: .ok)
|
||||
// }
|
||||
}
|
||||
|
||||
|
||||
extension Double
|
||||
{
|
||||
func truncate(places : Int)-> Double
|
||||
{
|
||||
return Double(floor(pow(10.0, Double(places)) * self)/pow(10.0, Double(places)))
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user