heftapp / graphql_codegen

MIT License
143 stars 53 forks source link

Fragment doesnt seem to work #315

Closed PhiFry closed 11 months ago

PhiFry commented 11 months ago

Flutter project pubspec.yaml:

dependencies: 
  graphql: ^5.1.3
dev_dependencies:
  graphql_codegen: ^0.13.7

We use Hasura as our GraphQL host. We have a core_users table which has columns (id, display_name).

In our schema.graphql file we have defined:

type User {
  id: bigint!
  display_name: String!
}

fragment userFields on User {
  id
  display_name
}

type Query {
  core_users: [User!]!
}

Then for our query:

query GetAllUsers() {
    users: core_users {
        ...userFields
    }
}

then build_runner build

When I then call _graphQLClient.query_GetAllUsers() I get error message saying that "id" is null. When I breakpoint into the generated parsing function I see that the data received only consists of __typename so of course its null.

I dug even deeper to view the actual query being sent to our GraphQL host and found that the query doesnt include the fragment fields but only the fragment name like this:

query GetAllUsers() {
    users: core_users {
        ...userFields
    }
}

I expected the query sent in the request to be this:

query GetAllUsers() {
    users: core_users {
        id
        display_name
    }
}

Removing the fragment and instead entering the fields manually in the query then everything works.

Is this the intended behaviour?

If it is then how can I get fragments to work? Do the GraphQL host need to specify the fragments?

github-actions[bot] commented 11 months ago

👋 @PhiFry Thank you for raising an issue. I will investigate the issue and get back to you as soon as possible. Please make sure you have provided enough context.

This library is created and maintained by me, @budde377. Please consider supporting my work and ensure our survival by donating here.

budde377 commented 11 months ago

Thanks for reaching out @PhiFry. The code-generator should not update your query or inline any field selections. It should, however, append the fragment to your query and send it to the server. Something like

query GetAllUsers() {
    users: core_users {
        ...userFields
    }
}
fragment userFields on User {
  id
  display_name
}

It is then up to the server to handle this appropriately.

PhiFry commented 11 months ago

Thank you @budde377 for taking your time and explaining.

I can see now that I missed the fragment part of the built query and it does indeed exist. Our issue is that we didnt name the User type exactly like the Hasura one. I changed type User to type core_users and now it works.