Skip to content

Commit d45e43c

Browse files
committed
add code to deal with nested fragments
1 parent 9b27c0d commit d45e43c

1 file changed

Lines changed: 37 additions & 19 deletions

File tree

packages/apollo-codegen-core/src/loading.ts

Lines changed: 37 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -250,25 +250,10 @@ export function combineOperationsAndFragments(
250250
operations.forEach(operation => {
251251
const completeOperation: Array<
252252
OperationDefinitionNode | FragmentDefinitionNode
253-
> = [operation];
254-
255-
visit(operation, {
256-
[Kind.FRAGMENT_SPREAD]: node => {
257-
if (!node.name || node.name.kind !== "Name") {
258-
(errorLogger || console.warn)(
259-
`Fragment Spread must have a name ${node}`
260-
);
261-
}
262-
if (!fragments[node.name.value]) {
263-
(errorLogger || console.warn)(
264-
`Fragment ${
265-
node.name.value
266-
} is not defined. Please add the file containing the fragment to the set of included paths`
267-
);
268-
}
269-
completeOperation.push(fragments[node.name.value]);
270-
}
271-
});
253+
> = [
254+
operation,
255+
...Object.values(getNestedFragments(operation, fragments, errorLogger))
256+
];
272257

273258
fullOperations.push({
274259
kind: "Document",
@@ -277,3 +262,36 @@ export function combineOperationsAndFragments(
277262
});
278263
return fullOperations;
279264
}
265+
266+
function getNestedFragments(
267+
operation: OperationDefinitionNode | FragmentDefinitionNode,
268+
fragments: Record<string, FragmentDefinitionNode>,
269+
errorLogger?: (message: string) => void
270+
) {
271+
// Using an object ensures that we only include each fragment definition once.
272+
// We are assured that there will be no duplicate fragment names during the
273+
// extraction step
274+
const combination: Record<string, FragmentDefinitionNode> = {};
275+
visit(operation, {
276+
[Kind.FRAGMENT_SPREAD]: node => {
277+
if (!node.name || node.name.kind !== "Name") {
278+
(errorLogger || console.warn)(
279+
`Fragment Spread must have a name ${node}`
280+
);
281+
}
282+
if (!fragments[node.name.value]) {
283+
(errorLogger || console.warn)(
284+
`Fragment ${
285+
node.name.value
286+
} is not defined. Please add the file containing the fragment to the set of included paths`
287+
);
288+
}
289+
Object.assign(
290+
combination,
291+
getNestedFragments(fragments[node.name.value], fragments, errorLogger),
292+
{ [node.name.value]: fragments[node.name.value] }
293+
);
294+
}
295+
});
296+
return combination;
297+
}

0 commit comments

Comments
 (0)