~xenrox/10man-api

59bb3206ccb6e591acdd21b85501c79e8f159fca — Thorben Günther 10 months ago 11505ba
Add getTeams

If no id is given as an argument, this will return the teams from the
currently ongoing match.
M graph/generated/generated.go => graph/generated/generated.go +271 -0
@@ 49,6 49,7 @@ type ComplexityRoot struct {
		CreateUser  func(childComplexity int, input model.NewUser) int
		DeleteUser  func(childComplexity int, id int) int
		FinishMatch func(childComplexity int, winner string) int
		GetTeams    func(childComplexity int, id *int) int
		StartQueue  func(childComplexity int, teamspeakID string) int
		UpdateUser  func(childComplexity int, id int, input model.UserInput) int
	}


@@ 58,6 59,11 @@ type ComplexityRoot struct {
		UserByTs    func(childComplexity int, teamspeakID string) int
	}

	Teams struct {
		Team1 func(childComplexity int) int
		Team2 func(childComplexity int) int
	}

	User struct {
		Admin       func(childComplexity int) int
		Avatar      func(childComplexity int) int


@@ 78,6 84,7 @@ type MutationResolver interface {
	CreateMatch(ctx context.Context) (int, error)
	CancelMatch(ctx context.Context) (string, error)
	FinishMatch(ctx context.Context, winner string) (string, error)
	GetTeams(ctx context.Context, id *int) (*model.Teams, error)
}
type QueryResolver interface {
	UserBySteam(ctx context.Context, steamID string) (*model.User, error)


@@ 161,6 168,18 @@ func (e *executableSchema) Complexity(typeName, field string, childComplexity in

		return e.complexity.Mutation.FinishMatch(childComplexity, args["winner"].(string)), true

	case "Mutation.getTeams":
		if e.complexity.Mutation.GetTeams == nil {
			break
		}

		args, err := ec.field_Mutation_getTeams_args(context.TODO(), rawArgs)
		if err != nil {
			return 0, false
		}

		return e.complexity.Mutation.GetTeams(childComplexity, args["id"].(*int)), true

	case "Mutation.startQueue":
		if e.complexity.Mutation.StartQueue == nil {
			break


@@ 209,6 228,20 @@ func (e *executableSchema) Complexity(typeName, field string, childComplexity in

		return e.complexity.Query.UserByTs(childComplexity, args["teamspeakID"].(string)), true

	case "Teams.team1":
		if e.complexity.Teams.Team1 == nil {
			break
		}

		return e.complexity.Teams.Team1(childComplexity), true

	case "Teams.team2":
		if e.complexity.Teams.Team2 == nil {
			break
		}

		return e.complexity.Teams.Team2(childComplexity), true

	case "User.admin":
		if e.complexity.User.Admin == nil {
			break


@@ 332,6 365,11 @@ var sources = []*ast.Source{
    name: String
}

type Teams {
    team1: [User!]!
    team2: [User!]!
}

type Query {
    userBySteam(steamID: String!): User
    userByTS(teamspeakID: String!): User


@@ 360,6 398,7 @@ type Mutation {
    createMatch: Int!
    cancelMatch: String!
    finishMatch(winner: String!): String!
    getTeams(id: Int): Teams!
}
`, BuiltIn: false},
}


@@ 429,6 468,21 @@ func (ec *executionContext) field_Mutation_finishMatch_args(ctx context.Context,
	return args, nil
}

func (ec *executionContext) field_Mutation_getTeams_args(ctx context.Context, rawArgs map[string]interface{}) (map[string]interface{}, error) {
	var err error
	args := map[string]interface{}{}
	var arg0 *int
	if tmp, ok := rawArgs["id"]; ok {
		ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("id"))
		arg0, err = ec.unmarshalOInt2ᚖint(ctx, tmp)
		if err != nil {
			return nil, err
		}
	}
	args["id"] = arg0
	return args, nil
}

func (ec *executionContext) field_Mutation_startQueue_args(ctx context.Context, rawArgs map[string]interface{}) (map[string]interface{}, error) {
	var err error
	args := map[string]interface{}{}


@@ 870,6 924,48 @@ func (ec *executionContext) _Mutation_finishMatch(ctx context.Context, field gra
	return ec.marshalNString2string(ctx, field.Selections, res)
}

func (ec *executionContext) _Mutation_getTeams(ctx context.Context, field graphql.CollectedField) (ret graphql.Marshaler) {
	defer func() {
		if r := recover(); r != nil {
			ec.Error(ctx, ec.Recover(ctx, r))
			ret = graphql.Null
		}
	}()
	fc := &graphql.FieldContext{
		Object:     "Mutation",
		Field:      field,
		Args:       nil,
		IsMethod:   true,
		IsResolver: true,
	}

	ctx = graphql.WithFieldContext(ctx, fc)
	rawArgs := field.ArgumentMap(ec.Variables)
	args, err := ec.field_Mutation_getTeams_args(ctx, rawArgs)
	if err != nil {
		ec.Error(ctx, err)
		return graphql.Null
	}
	fc.Args = args
	resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) {
		ctx = rctx // use context from middleware stack in children
		return ec.resolvers.Mutation().GetTeams(rctx, args["id"].(*int))
	})
	if err != nil {
		ec.Error(ctx, err)
		return graphql.Null
	}
	if resTmp == nil {
		if !graphql.HasFieldError(ctx, fc) {
			ec.Errorf(ctx, "must not be null")
		}
		return graphql.Null
	}
	res := resTmp.(*model.Teams)
	fc.Result = res
	return ec.marshalNTeams2ᚖgitᚗxenroxᚗnetᚋאxenroxᚋ10manᚑapiᚋgraphᚋmodelᚐTeams(ctx, field.Selections, res)
}

func (ec *executionContext) _Query_userBySteam(ctx context.Context, field graphql.CollectedField) (ret graphql.Marshaler) {
	defer func() {
		if r := recover(); r != nil {


@@ 1019,6 1115,76 @@ func (ec *executionContext) _Query___schema(ctx context.Context, field graphql.C
	return ec.marshalO__Schema2ᚖgithubᚗcomᚋ99designsᚋgqlgenᚋgraphqlᚋintrospectionᚐSchema(ctx, field.Selections, res)
}

func (ec *executionContext) _Teams_team1(ctx context.Context, field graphql.CollectedField, obj *model.Teams) (ret graphql.Marshaler) {
	defer func() {
		if r := recover(); r != nil {
			ec.Error(ctx, ec.Recover(ctx, r))
			ret = graphql.Null
		}
	}()
	fc := &graphql.FieldContext{
		Object:     "Teams",
		Field:      field,
		Args:       nil,
		IsMethod:   false,
		IsResolver: false,
	}

	ctx = graphql.WithFieldContext(ctx, fc)
	resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) {
		ctx = rctx // use context from middleware stack in children
		return obj.Team1, nil
	})
	if err != nil {
		ec.Error(ctx, err)
		return graphql.Null
	}
	if resTmp == nil {
		if !graphql.HasFieldError(ctx, fc) {
			ec.Errorf(ctx, "must not be null")
		}
		return graphql.Null
	}
	res := resTmp.([]*model.User)
	fc.Result = res
	return ec.marshalNUser2ᚕᚖgitᚗxenroxᚗnetᚋאxenroxᚋ10manᚑapiᚋgraphᚋmodelᚐUserᚄ(ctx, field.Selections, res)
}

func (ec *executionContext) _Teams_team2(ctx context.Context, field graphql.CollectedField, obj *model.Teams) (ret graphql.Marshaler) {
	defer func() {
		if r := recover(); r != nil {
			ec.Error(ctx, ec.Recover(ctx, r))
			ret = graphql.Null
		}
	}()
	fc := &graphql.FieldContext{
		Object:     "Teams",
		Field:      field,
		Args:       nil,
		IsMethod:   false,
		IsResolver: false,
	}

	ctx = graphql.WithFieldContext(ctx, fc)
	resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) {
		ctx = rctx // use context from middleware stack in children
		return obj.Team2, nil
	})
	if err != nil {
		ec.Error(ctx, err)
		return graphql.Null
	}
	if resTmp == nil {
		if !graphql.HasFieldError(ctx, fc) {
			ec.Errorf(ctx, "must not be null")
		}
		return graphql.Null
	}
	res := resTmp.([]*model.User)
	fc.Result = res
	return ec.marshalNUser2ᚕᚖgitᚗxenroxᚗnetᚋאxenroxᚋ10manᚑapiᚋgraphᚋmodelᚐUserᚄ(ctx, field.Selections, res)
}

func (ec *executionContext) _User_id(ctx context.Context, field graphql.CollectedField, obj *model.User) (ret graphql.Marshaler) {
	defer func() {
		if r := recover(); r != nil {


@@ 2534,6 2700,11 @@ func (ec *executionContext) _Mutation(ctx context.Context, sel ast.SelectionSet)
			if out.Values[i] == graphql.Null {
				invalids++
			}
		case "getTeams":
			out.Values[i] = ec._Mutation_getTeams(ctx, field)
			if out.Values[i] == graphql.Null {
				invalids++
			}
		default:
			panic("unknown field " + strconv.Quote(field.Name))
		}


@@ 2597,6 2768,38 @@ func (ec *executionContext) _Query(ctx context.Context, sel ast.SelectionSet) gr
	return out
}

var teamsImplementors = []string{"Teams"}

func (ec *executionContext) _Teams(ctx context.Context, sel ast.SelectionSet, obj *model.Teams) graphql.Marshaler {
	fields := graphql.CollectFields(ec.OperationContext, sel, teamsImplementors)

	out := graphql.NewFieldSet(fields)
	var invalids uint32
	for i, field := range fields {
		switch field.Name {
		case "__typename":
			out.Values[i] = graphql.MarshalString("Teams")
		case "team1":
			out.Values[i] = ec._Teams_team1(ctx, field, obj)
			if out.Values[i] == graphql.Null {
				invalids++
			}
		case "team2":
			out.Values[i] = ec._Teams_team2(ctx, field, obj)
			if out.Values[i] == graphql.Null {
				invalids++
			}
		default:
			panic("unknown field " + strconv.Quote(field.Name))
		}
	}
	out.Dispatch()
	if invalids > 0 {
		return graphql.Null
	}
	return out
}

var userImplementors = []string{"User"}

func (ec *executionContext) _User(ctx context.Context, sel ast.SelectionSet, obj *model.User) graphql.Marshaler {


@@ 2948,6 3151,74 @@ func (ec *executionContext) marshalNString2string(ctx context.Context, sel ast.S
	return res
}

func (ec *executionContext) marshalNTeams2gitᚗxenroxᚗnetᚋאxenroxᚋ10manᚑapiᚋgraphᚋmodelᚐTeams(ctx context.Context, sel ast.SelectionSet, v model.Teams) graphql.Marshaler {
	return ec._Teams(ctx, sel, &v)
}

func (ec *executionContext) marshalNTeams2ᚖgitᚗxenroxᚗnetᚋאxenroxᚋ10manᚑapiᚋgraphᚋmodelᚐTeams(ctx context.Context, sel ast.SelectionSet, v *model.Teams) graphql.Marshaler {
	if v == nil {
		if !graphql.HasFieldError(ctx, graphql.GetFieldContext(ctx)) {
			ec.Errorf(ctx, "must not be null")
		}
		return graphql.Null
	}
	return ec._Teams(ctx, sel, v)
}

func (ec *executionContext) marshalNUser2ᚕᚖgitᚗxenroxᚗnetᚋאxenroxᚋ10manᚑapiᚋgraphᚋmodelᚐUserᚄ(ctx context.Context, sel ast.SelectionSet, v []*model.User) graphql.Marshaler {
	ret := make(graphql.Array, len(v))
	var wg sync.WaitGroup
	isLen1 := len(v) == 1
	if !isLen1 {
		wg.Add(len(v))
	}
	for i := range v {
		i := i
		fc := &graphql.FieldContext{
			Index:  &i,
			Result: &v[i],
		}
		ctx := graphql.WithFieldContext(ctx, fc)
		f := func(i int) {
			defer func() {
				if r := recover(); r != nil {
					ec.Error(ctx, ec.Recover(ctx, r))
					ret = nil
				}
			}()
			if !isLen1 {
				defer wg.Done()
			}
			ret[i] = ec.marshalNUser2ᚖgitᚗxenroxᚗnetᚋאxenroxᚋ10manᚑapiᚋgraphᚋmodelᚐUser(ctx, sel, v[i])
		}
		if isLen1 {
			f(i)
		} else {
			go f(i)
		}

	}
	wg.Wait()

	for _, e := range ret {
		if e == graphql.Null {
			return graphql.Null
		}
	}

	return ret
}

func (ec *executionContext) marshalNUser2ᚖgitᚗxenroxᚗnetᚋאxenroxᚋ10manᚑapiᚋgraphᚋmodelᚐUser(ctx context.Context, sel ast.SelectionSet, v *model.User) graphql.Marshaler {
	if v == nil {
		if !graphql.HasFieldError(ctx, graphql.GetFieldContext(ctx)) {
			ec.Errorf(ctx, "must not be null")
		}
		return graphql.Null
	}
	return ec._User(ctx, sel, v)
}

func (ec *executionContext) unmarshalNUserInput2gitᚗxenroxᚗnetᚋאxenroxᚋ10manᚑapiᚋgraphᚋmodelᚐUserInput(ctx context.Context, v interface{}) (model.UserInput, error) {
	res, err := ec.unmarshalInputUserInput(ctx, v)
	return res, graphql.ErrorOnPath(ctx, err)

M graph/model/models_gen.go => graph/model/models_gen.go +5 -0
@@ 9,6 9,11 @@ type NewUser struct {
	Name        *string `json:"name"`
}

type Teams struct {
	Team1 []*User `json:"team1"`
	Team2 []*User `json:"team2"`
}

type User struct {
	ID          int     `json:"id"`
	SteamID     string  `json:"steamID"`

M graph/schema.graphqls => graph/schema.graphqls +6 -0
@@ 8,6 8,11 @@ type User {
    name: String
}

type Teams {
    team1: [User!]!
    team2: [User!]!
}

type Query {
    userBySteam(steamID: String!): User
    userByTS(teamspeakID: String!): User


@@ 36,4 41,5 @@ type Mutation {
    createMatch: Int!
    cancelMatch: String!
    finishMatch(winner: String!): String!
    getTeams(id: Int): Teams!
}

M graph/schema.resolvers.go => graph/schema.resolvers.go +80 -0
@@ 388,6 388,86 @@ func (r *mutationResolver) FinishMatch(ctx context.Context, winner string) (stri
	return "FinishSuccess", nil
}

func (r *mutationResolver) GetTeams(ctx context.Context, id *int) (*model.Teams, error) {
	var teams model.Teams
	var team1, team2 []*model.User
	var err error
	var rows *sql.Rows

	tx, err := database.DB.Begin()
	if err != nil {
		return nil, database.CheckErrorCode(err)
	}
	defer tx.Rollback()

	query := `
	    SELECT "User".id, "User".steam_id, "User".teamspeak_id, "User".elo,
		"User".admin, "User".avatar, "User".name FROM (
	    SELECT unnest( array[ "Team".p1, "Team".p2, "Team".p3, "Team".p4, "Team".p5] )
        AS inner_query, status, "Match".id  FROM "Match"
		LEFT JOIN "Team" ON "Match".%s = "Team".id) AS member
	    LEFT JOIN "User" ON member.inner_query = "User".id`

	// Team 1
	if id != nil {
		// get match by id
		query += "\nWHERE member.id = $1"
		rows, err = tx.Query(fmt.Sprintf(query, "t1"), id)
	} else {
		// get ongoing match
		query += "\nWHERE member.status = 'ongoing'"
		rows, err = tx.Query(fmt.Sprintf(query, "t1"))
	}

	if err != nil {
		return nil, database.CheckErrorCode(err)
	}
	defer rows.Close()

	for rows.Next() {
		var user model.User
		if err := rows.Scan(&user.ID, &user.SteamID, &user.TeamspeakID,
			&user.Elo, &user.Admin, &user.Avatar, &user.Name); err != nil {
			return nil, database.CheckErrorCode(err)
		}

		team1 = append(team1, &user)
	}
	if err = rows.Err(); err != nil {
		return nil, database.CheckErrorCode(err)
	}

	// Team 2
	if id != nil {
		// get match by id
		rows, err = tx.Query(fmt.Sprintf(query, "t2"), id)
	} else {
		// get ongoing match
		rows, err = tx.Query(fmt.Sprintf(query, "t2"))
	}

	if err != nil {
		return nil, database.CheckErrorCode(err)
	}
	defer rows.Close()

	for rows.Next() {
		var user model.User
		if err := rows.Scan(&user.ID, &user.SteamID, &user.TeamspeakID,
			&user.Elo, &user.Admin, &user.Avatar, &user.Name); err != nil {
			return nil, database.CheckErrorCode(err)
		}

		team2 = append(team2, &user)
	}
	if err = rows.Err(); err != nil {
		return nil, database.CheckErrorCode(err)
	}

	teams.Team1, teams.Team2 = team1, team2
	return &teams, nil
}

func (r *queryResolver) UserBySteam(ctx context.Context, steamID string) (*model.User, error) {
	var user model.User
	user.SteamID = steamID