Skip to content

Commit

Permalink
Add filtering of teams by user ID
Browse files Browse the repository at this point in the history
  • Loading branch information
thehowl committed Mar 8, 2018
1 parent e870591 commit eb587b8
Show file tree
Hide file tree
Showing 2 changed files with 36 additions and 6 deletions.
20 changes: 19 additions & 1 deletion http/api/teams.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,11 +2,28 @@ package api

import (
"zxq.co/ripple/misirlou-api/http"
"zxq.co/ripple/misirlou-api/models"
)

// Teams fetches the teams that are playing in the given tournament ID.
func Teams(c *http.Context) {
teams, err := c.DB.Teams(c.QueryInt("tournament"), c.QueryInt("p"))
teams(c, models.TeamFilters{
Tournament: c.QueryInt("tournament"),
})
}

// TeamsInTournament returns all the teams in a tournament, which basically is
// sugar for calling Teams giving a tournament.
func TeamsInTournament(c *http.Context) {
teams(c, models.TeamFilters{
Tournament: c.ParamInt("id"),
ForceTournament: true,
})
}

func teams(c *http.Context, filters models.TeamFilters) {
filters.Member = c.QueryInt("member")
teams, err := c.DB.Teams(filters, c.QueryInt("p"))
if err != nil {
c.Error(err)
return
Expand All @@ -28,6 +45,7 @@ func Team(c *http.Context) {
}

func init() {
http.GET("/tournaments/:id/teams", TeamsInTournament)
http.GET("/teams", Teams)
http.GET("/teams/:id", Team)
}
22 changes: 17 additions & 5 deletions models/team.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
package models

import "time"
import (
"time"
)

// Team represents a team playing in Misirlou.
type Team struct {
Expand All @@ -11,13 +13,23 @@ type Team struct {
CreatedAt time.Time `json:"created_at"`
}

// TODO: we should check that the team's tournament is = 0.
// TODO: we should check that the team's tournament status is not 0.

// TeamFilters are options that can be passed to Teams for filtering teams.
type TeamFilters struct {
Tournament int
ForceTournament bool
Member int
}

// Teams returns at most 50 teams with the specified page.
func (db *DB) Teams(tournID, page int) ([]Team, error) {
func (db *DB) Teams(filters TeamFilters, page int) ([]Team, error) {
d := db.db
if tournID != 0 {
d = d.Where("tournament = ?", tournID)
if filters.ForceTournament || filters.Tournament != 0 {
d = d.Where("tournament = ?", filters.Tournament)
}
if filters.Member != 0 {
d = d.Joins("INNER JOIN team_users ON team_users.team = teams.id AND team_users.user = ?", filters.Member)
}
teams := make([]Team, 0, 50)
d = d.Offset(positivePage(page) * 50).Limit(50).Find(&teams)
Expand Down

0 comments on commit eb587b8

Please sign in to comment.