Files
cod-backend/Sources/App/Controllers/MatchController.swift
2021-08-04 16:32:17 -05:00

88 lines
2.3 KiB
Swift

//
// MatchController.swift
// App
//
// Created by Michael Simard on 12/13/20.
//
import Foundation
import Fluent
import Vapor
struct MatchController: RouteCollection {
func boot(routes: RoutesBuilder) throws {
let matchRoute = routes.grouped("cod-tracker","api", "match")
matchRoute.delete("delete", "id",":id", use: deleteMatch)
matchRoute.post("update", "id",":id", use: updateMatch)
matchRoute.post("add", use: logMatch)
}
func updateMatch(req: Request) throws -> EventLoopFuture<HTTPStatus> {
guard let id = req.parameters.get("id", as: UUID.self) else {
throw Abort(.badRequest)
}
let newMatch = try req.content.decode(Match.self)
return Match.find(id, on: req.db)
.unwrap(or: Abort(.notFound))
.flatMap {
$0.update(newMatch: newMatch)
return $0.save(on: req.db)
}
.map {
req.application.threadPool.runIfActive(eventLoop: req.eventLoop.next()) {
DBHelpers.relcalulateRecords(db: req.db) { MessagePort in}
}
return .ok
}
}
func deleteMatch(req: Request) throws -> EventLoopFuture<HTTPStatus> {
guard let id = req.parameters.get("id", as: UUID.self) else {
throw Abort(.badRequest)
}
return Match.find(id, on: req.db)
.unwrap(or: Abort(.notFound))
.flatMap { $0.delete(on: req.db) }
.map {
req.application.threadPool.runIfActive(eventLoop: req.eventLoop.next()) {
DBHelpers.relcalulateRecords(db: req.db) { MessagePort in}
}
return .ok
}
}
func logMatch(req: Request) throws -> EventLoopFuture<Match> {
let newMatch = try req.content.decode(Match.self)
return newMatch.save(on: req.db).map {
req.application.threadPool.runIfActive(eventLoop: req.eventLoop.next()) {
DBHelpers.relcalulateRecords(db: req.db) { MessagePort in}
}
return newMatch
}
}
}