2

I'm using GraphQL Code Generator to create typed DocumentNode fragments e.g.

export const MMovieConnectionFragmentDoc = {"kind":"Document","definitions":[{"kind":"FragmentDefinition","name":{"kind":"Name","value":"MMovieConnection"},"typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"MMovieConnection"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"edges"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"node"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"id"}},{"kind":"Field","name":{"kind":"Name","value":"mMovieActors"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"id"}}]}}]}}]}}]}}]} as unknown as DocumentNode<MMovieConnectionFragment, unknown>;

I'm trying to use this fragment to create a simple GraphQL query e.g.

gql`query myQuery {
      myQuery {
          ...MMovieConnection
      }
  }
  ${MMovieConnectionFragmentDoc}
`

But this generates error: Cannot read properties of undefined (reading 'source')

If I create a fragment in this standard way, the query is created successfully:

fieldsFragment = gql`fragment MMovieConnection on MMovieConnection {
    edges {
        node {
            id
        }
    }
}`;

The standard fragment object is equivalent to the MMovieConnectionFragmentDoc object but has an additional loc property that includes a source property.

loc: {
    start: 0,
    end: 239,
    source: {
      body: "fragment MMovieConnection on MMovieConnection {\n            edges {\n                node {\n                    id\n                    mMovieActors {\n                        id\n                    }\n                }\n            }\n        }",
      name: "GraphQL request",
      locationOffset: {
        line: 1,
        column: 1,
      },
    },
  },

So gql seems to need the loc and source property when using fragments in queries.

But is there a way to use MMovieConnectionFragmentDoc to create a query?

1 Answer 1

3

Converting the fragment back to a string and then wrapping in gql works.

import * as graphql from 'graphql';

fragment = gql`${graphql.print(MMovieConnectionFragmentDoc)}`;

gql`query myQuery {
        myQuery {
            ...myFragmentName
        }
    }
    ${fragment}
`;
Sign up to request clarification or add additional context in comments.

2 Comments

Are you aware of any way to get the type of the query's variables from the TypedDocumentNode?
Did you find an answer to this? Are you able to provide a more detailed example?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.