Skip to content

Commit

Permalink
Fix bug where a selection from a fragment may return that field in th…
Browse files Browse the repository at this point in the history
…e parent query
  • Loading branch information
jerelmiller committed Aug 21, 2024
1 parent bc5326e commit 9a8ef88
Show file tree
Hide file tree
Showing 2 changed files with 52 additions and 1 deletion.
41 changes: 41 additions & 0 deletions src/core/__tests__/masking.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -106,6 +106,47 @@ describe("maskOperation", () => {
expect(data).toEqual({ user: { __typename: "User", id: 1 } });
});

test("masks fragments from nested objects when query gets fields from same object", () => {
const query = gql`
query {
user {
__typename
profile {
__typename
id
}
...UserFields
}
}
fragment UserFields on User {
profile {
__typename
id
fullName
}
}
`;

const data = maskOperation(
deepFreeze({
user: {
__typename: "User",
profile: { __typename: "Profile", id: "1", fullName: "Test User" },
},
}),
query,
createFragmentMatcher(new InMemoryCache())
);

expect(data).toEqual({
user: {
__typename: "User",
profile: { __typename: "Profile", id: "1" },
},
});
});

test("deep freezes the masked result if the original data is frozen", () => {
const query = gql`
query {
Expand Down
12 changes: 11 additions & 1 deletion src/core/masking.ts
Original file line number Diff line number Diff line change
Expand Up @@ -149,13 +149,23 @@ function maskSelectionSet(
memo[keyName] = data[keyName];

if (childSelectionSet) {
const [masked, childChanged] = maskSelectionSet(
let [masked, childChanged] = maskSelectionSet(
data[keyName],
childSelectionSet,
context,
__DEV__ ? `${path || ""}.${keyName}` : void 0
);

// This check prevents cases where masked fields may accidentally be
// returned as part of this object when the fragment also selects
// additional fields from the same child selection.
if (
!childChanged &&
Object.keys(masked).length !== Object.keys(data[keyName]).length
) {
childChanged = true;
}

if (childChanged) {
memo[keyName] = masked;
changed = true;
Expand Down

0 comments on commit 9a8ef88

Please sign in to comment.