Skip to content

Commit

Permalink
Fix relayStylePagination bug when using after
Browse files Browse the repository at this point in the history
  • Loading branch information
srmagura committed Jun 9, 2022
1 parent 538b795 commit 0fff20e
Show file tree
Hide file tree
Showing 2 changed files with 36 additions and 8 deletions.
22 changes: 22 additions & 0 deletions src/utilities/policies/__tests__/relayStylePagination.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -153,6 +153,28 @@ describe('relayStylePagination', () => {
});
});

it("replaces the existing data if a query using `after` is repeated", () => {
const page = {
edges: [{ cursor: "alpha", node: makeReference("fakeAlpha") }],
pageInfo: {
hasPreviousPage: false,
hasNextPage: true,
startCursor: "alpha",
endCursor: "alpha",
},
};

const result = merge(page, page, {
...options,
args: {
// Represents the cursor that comes immediately before 'alpha'
after: "zeta",
},
});

expect(result).toEqual(page);
});

it('should maintain existing PageInfo when adding a page', () => {
const existingEdges = [
{ cursor: 'alpha', node: makeReference("fakeAlpha") },
Expand Down
22 changes: 14 additions & 8 deletions src/utilities/policies/pagination.ts
Original file line number Diff line number Diff line change
Expand Up @@ -188,27 +188,33 @@ export function relayStylePagination<TNode = Reference>(
}
}

let prefix = existing.edges;
let suffix: typeof prefix = [];
let prefix: TRelayEdge<TNode>[] = [];
let suffix: TRelayEdge<TNode>[] = [];

if (args && args.after) {
// This comparison does not need to use readField("cursor", edge),
// because we stored the cursor field of any Reference edges as an
// extra property of the Reference object.
const index = prefix.findIndex(edge => edge.cursor === args.after);
const index = existing.edges.findIndex(
edge => edge.cursor === args.after,
);
if (index >= 0) {
prefix = prefix.slice(0, index + 1);
prefix = existing.edges.slice(0, index + 1);
// suffix = []; // already true
}
} else if (args && args.before) {
const index = prefix.findIndex(edge => edge.cursor === args.before);
suffix = index < 0 ? prefix : prefix.slice(index);
prefix = [];
const index = existing.edges.findIndex(
edge => edge.cursor === args.before,
);
suffix = index < 0 ? existing.edges : existing.edges.slice(index);
// prefix = []; // already true
} else if (incoming.edges) {
// If we have neither args.after nor args.before, the incoming
// edges cannot be spliced into the existing edges, so they must
// replace the existing edges. See #6592 for a motivating example.
prefix = [];
// prefix = []; // already true
} else {
prefix = existing.edges;
}

const edges = [
Expand Down

0 comments on commit 0fff20e

Please sign in to comment.