hasura / go-graphql-client

Package graphql provides a GraphQL client implementation.
MIT License
405 stars 94 forks source link

mutation query doesn't allow optional params #95

Closed jorgevillafuerte closed 1 year ago

jorgevillafuerte commented 1 year ago

Hello! I'm have this graphql tag graphql:"createProducts(name: $name, url: $url, callbackUrl: $callbackUrl, email: $email)" and this variables map

        vars := map[string]interface{}{
        "name": graphql.String(storefront),
        "url":      graphql.String(location),
    }

    email := config.email
    if len(email) > 0 {
        vars["email"] = graphql.String(email)
    }

    callbackUrl := config.CallbackUrl
    if len(callbackUrl) > 0 {
        vars["callbackUrl"] = graphql.String(callbackUrl)
    }

    if err := i.client.Mutate(ctx, mutation, vars); err != nil {
            return err
    }

if config.CallbackUrl is empty, the result mutation is this, missing declare $callbackUrl as String

mutation (
  $email: String!
  $url: String!
  $name: String!
) {
  createProducts(
    name: $name
    url: $url
    email: $email
    callbackUrl: $callbackUrl
  ) {
    name
  }
}

if I change vars maps, adding "callbackUrl" as (*graphql.String)(nil), the variable declaration has the value $callbackUrl as String

vars := MutationVars{
        "name": graphql.String(storefront),
        "url":        graphql.String(location),
        "callbackUrl":    (*graphql.String)(nil),
    }

but the mutation return this error "'callbackUrl' must be a string"

There is no way to create a variable in our mutation query and don't send it. Or is no dynamic way to change the graphql tag

hgiasac commented 1 year ago

I tried your mutation, and the output is expected.


var mutation struct {
    CreateProducts struct {
        Name string
    } `graphql:"createProducts(name: $name, url: $url, email: $email, callbackUrl: $callbackUrl)"`
}

variables = map[string]interface{}{
    "name":        "foo",
    "email":       "bar",
    "callbackUrl": (*string)(nil),
}
mutation ($callbackUrl:String$email:String!$name:String!){
  createProducts(name: $name, url: $url, email: $email, callbackUrl: $callbackUrl) {
    name
  }
}

We have to input the nil variable because the library needs to infer the variable type and translate it to the equivalent GraphQL type. If you want to build the GraphQL query dynamically yourself, you can use the Exec method.

jorgevillafuerte commented 1 year ago

thanks! That works. I'm closing the issue