Skip to content
This repository has been archived by the owner on Sep 3, 2021. It is now read-only.

Check if the fragment already exists before pushing into selection array. #415

Merged
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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