Reputation: 3071
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?
Upvotes: 2
Views: 1646
Reputation: 3071
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}
`;
Upvotes: 2