Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Allow registering named fragments with InMemoryCache to support using ...FragmentName in queries without redeclaring FragmentName in every query #9764

Merged
merged 10 commits into from
Sep 21, 2022
Merged
12 changes: 9 additions & 3 deletions src/utilities/graphql/fragments.ts
Original file line number Diff line number Diff line change
@@ -108,6 +108,9 @@ export interface FragmentMap {
[fragmentName: string]: FragmentDefinitionNode;
}

export type FragmentMapFunction =
(fragmentName: string) => FragmentDefinitionNode | null;

// Utility function that takes a list of fragment definitions and makes a hash out of them
// that maps the name of the fragment to the fragment definition.
export function createFragmentMap(
@@ -122,14 +125,17 @@ export function createFragmentMap(

export function getFragmentFromSelection(
selection: SelectionNode,
fragmentMap?: FragmentMap,
fragmentMap?: FragmentMap | FragmentMapFunction,
): InlineFragmentNode | FragmentDefinitionNode | null {
switch (selection.kind) {
case 'InlineFragment':
return selection;
case 'FragmentSpread': {
const fragment = fragmentMap && fragmentMap[selection.name.value];
invariant(fragment, `No fragment named ${selection.name.value}.`);
const fragmentName = selection.name.value;
const fragment = typeof fragmentMap === "function"
? fragmentMap(fragmentName)
: fragmentMap && fragmentMap[fragmentName];
invariant(fragment, `No fragment named ${fragmentName}.`);
return fragment!;
}
default:
1 change: 1 addition & 0 deletions src/utilities/index.ts
Original file line number Diff line number Diff line change
@@ -14,6 +14,7 @@ export {

export {
FragmentMap,
FragmentMapFunction,
createFragmentMap,
getFragmentQueryDocument,
getFragmentFromSelection,