Skip to content

Commit

Permalink
Check if the fragment already exists before pushing into selection ar…
Browse files Browse the repository at this point in the history
…ray.

Fixes neo4j-graphql#412
  • Loading branch information
François Menet committed Apr 17, 2020
1 parent 7ecf49d commit 2fc487a
Showing 1 changed file with 11 additions and 8 deletions.
19 changes: 11 additions & 8 deletions src/selections.js
Original file line number Diff line number Diff line change
Expand Up @@ -741,26 +741,26 @@ const mergeInterfacedObjectFragments = ({
};

const mergeFragmentedSelections = ({ selections = [] }) => {
const subSelecionFieldMap = {};
const subSelectionFieldMap = {};
const fragments = [];
selections.forEach(selection => {
const fieldKind = selection.kind;
if (fieldKind === Kind.FIELD) {
const fieldName = selection.name.value;
if (!subSelecionFieldMap[fieldName]) {
if (!subSelectionFieldMap[fieldName]) {
// initialize entry for this composing type
subSelecionFieldMap[fieldName] = selection;
subSelectionFieldMap[fieldName] = selection;
} else {
const alreadySelected = subSelecionFieldMap[fieldName].selectionSet
? subSelecionFieldMap[fieldName].selectionSet.selections
const alreadySelected = subSelectionFieldMap[fieldName].selectionSet
? subSelectionFieldMap[fieldName].selectionSet.selections
: [];
const selected = selection.selectionSet
? selection.selectionSet.selections
: [];
// If the field has a subselection (relationship field)
if (alreadySelected.length && selected.length) {
const selections = [...alreadySelected, ...selected];
subSelecionFieldMap[
subSelectionFieldMap[
fieldName
].selectionSet.selections = mergeFragmentedSelections({
selections
Expand All @@ -769,11 +769,14 @@ const mergeFragmentedSelections = ({ selections = [] }) => {
}
} else {
// Persist all fragments, to be merged later
fragments.push(selection);
// If we already have this fragment, skip it.
if (!fragments.some(anyElement => anyElement === selection)) {
fragments.push(selection);
}
}
});
// Return the aggregation of all fragments and merged relationship fields
return [...Object.values(subSelecionFieldMap), ...fragments];
return [...Object.values(subSelectionFieldMap), ...fragments];
};

export const getDerivedTypes = ({
Expand Down

0 comments on commit 2fc487a

Please sign in to comment.