Skip to content

Commit

Permalink
add api call to dump all battle data as json
Browse files Browse the repository at this point in the history
  • Loading branch information
thomasf committed Apr 17, 2024
1 parent f8c6f3c commit 3bccaa8
Showing 1 changed file with 38 additions and 0 deletions.
38 changes: 38 additions & 0 deletions httpserver.go
Original file line number Diff line number Diff line change
Expand Up @@ -90,6 +90,7 @@ func (server *Server) RegisterHandlers(h *http.ServeMux, apiKey string, battlesF
h.Handle("/api/vote/", ClientIDMiddleware()(server.Vote()))
h.Handle("/api/unvote/", ClientIDMiddleware()(server.UnVote()))

h.Handle("/api/battles/{name}/", authMiddleware(server.GetBattleData()))
h.Handle("/api/scan/", authMiddleware(server.Scan()))
h.Handle("/api/open/{name}/", authMiddleware(server.OpenBattle()))
h.Handle("/api/close/{name}/", authMiddleware(server.CloseBattle()))
Expand Down Expand Up @@ -593,6 +594,43 @@ func (s *Server) Scan() AppHandler {
}
}

// BattleDataResponse .
type BattleDataResponse struct {
Battle db.Battle
Votes []db.Votes
ScoresSum map[string]int
}

func (s *Server) GetBattleData() AppHandler {

return func(w http.ResponseWriter, r *http.Request) error {
ctx := r.Context()
name := r.PathValue("name")
battle, err := s.DB.GetBattle(name)
if err != nil {
return err
}
if battle == nil {
return db.NotFound
}

allVotes, err := s.DB.GetAllVotes(name)
if err != nil {
return err
}

sumScores := db.SumScores(allVotes)
battle.Entries.SortByScore(sumScores)
WriteJSONResponse(ctx, w, http.StatusOK,
BattleDataResponse{
Votes: allVotes,
Battle: *battle,
ScoresSum: sumScores,
})
return nil
}
}

var upgrader = websocket.Upgrader{
ReadBufferSize: 10 * 1024,
WriteBufferSize: 10 * 1024,
Expand Down

0 comments on commit 3bccaa8

Please sign in to comment.