github-community-projects / graphql-client

A Ruby library for declaring, composing and executing GraphQL queries
MIT License
45 stars 219 forks source link

graphql-client .parse function creates invalid GraphQL syntax #21

Closed nowakoo closed 5 months ago

nowakoo commented 8 months ago

I have the following GraphQL code:

#Creates auth token needed to access the API
mutation GenerateKey($email: String!, $password: String!) {
  authenticate(email: $email, password: $password) {
    success
    errors {messages, field}
    result {key}
  }
}

#Send out email
mutation ForgotPassword($email: String!) {
  forgotPassword(email: $email) {
    success
    errors {messages, field}
  }
}

#Updates password, Key is not the auth token it comes from the reset email
mutation ResetPassword($email: String!, $key: String!, $password: String!) {
  resetPassword(email: $email, key: $key, password: $password) {
    success
    errors {messages, field}
  }
}

I defined GraphQL client as client and I parse the code above: mutations = client.parse(graphql_code), which returns a Module with three constants: GenerateKey,ForgotPassword,ResetPassword - GraphQL::Client::OperationDefinition objects. I couldn't execute this mutation with client.query(mutations.const_get(:GenerateKey), variables: { email: 'my_email@example.com', password: 'my_pass'}), as I received the following error:

#<GraphQL::Client::Errors @messages={"data"=>["Syntax Error: Expected '$', found Name 'email'."]} @details={"data"=>[{"message"=>"Syntax Error: Expected '$', found Name 'email'.", "locations"=>[{"line"=>2, "column"=>16}], "normalizedPath"=>["data"]}]}>

So I took a look at executed query using mutations.const_get(:GenerateKey).document.to_query_string and received:

mutation #<Module:0x0000000107b5ef70>__GenerateKey($email: String!, $password: String!) {
  authenticate(email: $email, password: $password) {
    success
    errors {
      messages
      field
    }
    result {
      key
    }
  }
}

#<Module:0x0000000107b5ef70>__GenerateKey mutation name is not a valid GraphQL syntax. Is there a way to workaround it?

rmosolgo commented 8 months ago

It creates the query name based on the generated module's name in Ruby. For example, if you did:

Mutations = client.parse(graphql_code)

Then it would generate Mutations__GenerateKey. For that to work, the module must be given a constant name. Does it work for you to update your code to assign constants?

rmosolgo commented 5 months ago

I hope you found something that works for you!