Skip to content

Instantly share code, notes, and snippets.

@robertoandres24
Forked from mattmazzola/schema.ts
Created December 7, 2020 04:15
Show Gist options
  • Save robertoandres24/539fffea1ad6821757b32326a41d362a to your computer and use it in GitHub Desktop.
Save robertoandres24/539fffea1ad6821757b32326a41d362a to your computer and use it in GitHub Desktop.
GraphQL Paginated Query Implementation
units: {
type: pagination.Page(Unit),
description: "Return the 'first' X number of items 'after' the specified cursor'",
args: {
first: {
type: graphql.GraphQLInt,
description: "Limits the number of results returned in the page. Defaults to 10."
},
after: {
type: graphql.GraphQLString,
description: "The cursor value of an item returned in previous page. An alternative to in integer offset."
}
},
resolve: function (root: any, { first = 10, after } : { first: number, after: string }) {
let afterIndex: number = 0;
// Get ID from after argument or default to first item.
if (typeof after === "string") {
let id = pagination.convertCursorToNodeId(after);
if (typeof id === "number") {
const matchingIndex = utilities.findIndex(unit => unit.id === id, balanceData.units);
if (matchingIndex != -1) {
afterIndex = matchingIndex;
}
}
}
// Add 1 to exclude item matching after index.
const sliceIndex = afterIndex + 1;
const edges = balanceData.units
.slice(sliceIndex, sliceIndex + first)
.map(node => ({
node,
cursor: pagination.convertNodeToCursor(node)
}));
const startCursor = edges.length > 0 ? pagination.convertNodeToCursor(edges[0].node) : null;
const endCursor = edges.length > 0 ? pagination.convertNodeToCursor(edges[edges.length-1].node) : null;
const hasNextPage = balanceData.units.length > sliceIndex + first;
return {
totalCount: balanceData.units.length,
edges,
pageInfo: {
startCursor,
endCursor,
hasNextPage
}
};
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment