-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
56 lines (51 loc) · 1.33 KB
/
index.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
import {
GraphQLInputObjectType,
GraphQLBoolean,
GraphQLString,
GraphQLInt,
} from "graphql";
import _ from "lodash";
export const paginationInputType = new GraphQLInputObjectType({
name: "PaginationInput",
description: "Input definition for pagination",
fields: {
page: {
description: "Page number",
type: GraphQLInt,
},
rowsPerPage: {
description: "Maximum number of rows to return for each page.",
type: GraphQLInt,
},
sortBy: {
description: "Object key to sort by.",
type: GraphQLString,
},
descending: {
description: "Set true to change sort order to descending",
type: GraphQLBoolean,
},
},
});
export function paginationResolver(
data,
args,
{indexOffset: indexOffset = 0} = {}
) {
let {
page: page = 0,
rowsPerPage: rowsPerPage = 10,
sortBy: sortBy = null,
descending: descending = false,
} = args || {};
if (rowsPerPage === 0) throw new Error("pageSize cannot be less than one");
if (!rowsPerPage || rowsPerPage === -1) {
rowsPerPage = data.length;
page = 0;
}
let pageOffet = Math.max(0, page + indexOffset);
let sortOrder = descending ? "desc" : "asc";
let sorted = _.orderBy(data, [sortBy], [sortOrder]);
let chunked = _.chunk(sorted, parseInt(rowsPerPage));
return chunked[parseInt(pageOffet)];
}