Skip to content

Instantly share code, notes, and snippets.

@oieduardorabelo
Last active March 7, 2019 12:39
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save oieduardorabelo/5d353958802aa00b8517f8f1e1b12057 to your computer and use it in GitHub Desktop.
Save oieduardorabelo/5d353958802aa00b8517f8f1e1b12057 to your computer and use it in GitHub Desktop.
Relay Inspired Pagination
const mockData = require("./mock-data.json");
const resolvers = {
Query: {
courses: (parent, args, context) => {
let edges = mockData;
let first = args.first;
let after = args.after;
let before = args.before;
let last = args.last;
let hasPreviousPage = false;
let hasNextPage = false;
if (typeof after === 'string') {
let opaqueCursor = Number(Buffer.from(after, 'base64').toString('ascii'));
let edgeIndex = mockData.findIndex(data => data.id === opaqueCursor);
if (edgeIndex !== -1) {
edges = edges.slice(edgeIndex + 1)
}
}
if (typeof before === 'string') {
let opaqueCursor = Number(Buffer.from(before, 'base64').toString('ascii'));
let edgeIndex = mockData.findIndex(data => data.id === opaqueCursor);
if (edgeIndex !== -1) {
edges = edges.slice(0, edgeIndex);
}
}
if (typeof first !== "undefined" && first < 0) {
throw new Error('"first" should be gth 0');
}
if (typeof last !== "undefined" && last < 0) {
throw new Error('"last" should be gth 0');
}
if (edges.length > first) {
hasNextPage = edges.length > first;
edges = edges.slice(0, first);
}
if (edges.length > last) {
edges = edges.slice(edges.length - last, edges.length + 1);
}
let start = 0;
let startCursor = null;
let endCursor = null;
edges = edges.map((data, index) => {
endCursor = Buffer.from(`${data.id}`).toString('base64');
if (index === 0) {
startCursor = endCursor
}
return {
cursor: endCursor,
node: data
};
});
return {
totalCount: edges.length,
edges,
pageInfo: {
startCursor,
endCursor,
hasPreviousPage,
hasNextPage
}
};
}
}
};
module.exports = resolvers;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment