From 5658905dee0d01b3cd57c69e7293f23f1707b0d1 Mon Sep 17 00:00:00 2001 From: Rafael Ferreira Date: Sat, 1 Nov 2025 09:04:03 +0100 Subject: [PATCH] Add support to send variables for GraphQL queries --- graphql.go | 3 ++- graphql_test.go | 40 ++++++++++++++++++++++++++++++++++++++++ 2 files changed, 42 insertions(+), 1 deletion(-) diff --git a/graphql.go b/graphql.go index 41c64d06..18fd6c9a 100644 --- a/graphql.go +++ b/graphql.go @@ -22,7 +22,8 @@ type ( } GraphQLQuery struct { - Query string `json:"query"` + Query string `json:"query"` + Variables map[string]any `json:"variables,omitempty"` } GenericGraphQLErrors struct { diff --git a/graphql_test.go b/graphql_test.go index c32ef57f..5ff9b188 100644 --- a/graphql_test.go +++ b/graphql_test.go @@ -16,6 +16,7 @@ func TestGraphQL_Do_Success(t *testing.T) { mux, client := setup(t) mux.HandleFunc("/api/graphql", func(w http.ResponseWriter, r *http.Request) { testMethod(t, r, http.MethodPost) + testJSONBody(t, r, `{ "query": "query { project(fullPath: \"gitlab-org/gitlab\") { id } }" }`) fmt.Fprint(w, ` { "data": { @@ -42,6 +43,45 @@ func TestGraphQL_Do_Success(t *testing.T) { assert.Equal(t, "any-id", response.Data.Project.ID) } +func TestGraphQL_Do_Success_With_Variables(t *testing.T) { + t.Parallel() + + // GIVEN + mux, client := setup(t) + mux.HandleFunc("/api/graphql", func(w http.ResponseWriter, r *http.Request) { + testMethod(t, r, http.MethodPost) + testJSONBody(t, r, `{ "query": "query ($projectPath: ID!) { project(fullPath: $projectPath) { id } }", "variables": { "projectPath": "gitlab-org/gitlab" } }`) + fmt.Fprint(w, ` + { + "data": { + "project": { + "id": "any-id" + } + } + } + `) + }) + + // WHEN + var response struct { + Data struct { + Project struct { + ID string `json:"id"` + } `json:"project"` + } `json:"data"` + } + _, err := client.GraphQL.Do( + GraphQLQuery{ + Query: `query ($projectPath: ID!) { project(fullPath: $projectPath) { id } }`, + Variables: map[string]any{"projectPath": "gitlab-org/gitlab"}, + }, + &response) + + // THEN + require.NoError(t, err) + assert.Equal(t, "any-id", response.Data.Project.ID) +} + func TestGraphQL_Do_ErrorWithMessages(t *testing.T) { t.Parallel() -- GitLab