/
PgConnectionTotalCount.js
73 lines (69 loc) · 1.94 KB
/
PgConnectionTotalCount.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
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
// @flow
import type { Plugin } from "graphile-build";
export default (function PgConnectionTotalCount(builder) {
builder.hook(
"GraphQLObjectType:fields",
(fields, build, context) => {
const {
extend,
inflection,
graphql: { GraphQLInt, GraphQLNonNull },
pgSql: sql,
} = build;
const {
scope: { isPgRowConnectionType, pgIntrospection: table, nodeType },
fieldWithHooks,
Self,
} = context;
if (!isPgRowConnectionType) {
return fields;
}
const nodeTypeName =
nodeType && nodeType.name
? nodeType.name
: table && table.kind === "class"
? inflection.tableType(table)
: null;
if (!nodeTypeName) {
return fields;
}
return extend(
fields,
{
totalCount: fieldWithHooks(
"totalCount",
({ addDataGenerator }) => {
addDataGenerator(() => {
return {
pgAggregateQuery: aggregateQueryBuilder => {
aggregateQueryBuilder.select(
sql.fragment`count(1)`,
"totalCount"
);
},
};
});
return {
description: build.wrapDescription(
`The count of *all* \`${nodeTypeName}\` you could get from the connection.`,
"field"
),
type: new GraphQLNonNull(GraphQLInt),
resolve(parent) {
return (
(parent.aggregates && parent.aggregates.totalCount) || 0
);
},
};
},
{
isPgConnectionTotalCountField: true,
}
),
},
`Adding totalCount to connection '${Self.name}'`
);
},
["PgConnectionTotalCount"]
);
}: Plugin);