-
Notifications
You must be signed in to change notification settings - Fork 10.3k
/
Copy pathbuild-connection-fields.js
111 lines (105 loc) · 3.16 KB
/
build-connection-fields.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
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
// @flow
const _ = require(`lodash`)
const {
GraphQLInt,
GraphQLList,
GraphQLString,
GraphQLEnumType,
} = require(`graphql`)
const {
connectionArgs,
connectionDefinitions,
connectionFromArray,
} = require(`graphql-skip-limit`)
const { buildFieldEnumValues } = require(`./data-tree-utils`)
module.exports = type => {
const enumValues = buildFieldEnumValues(type.nodes)
const { connectionType: groupConnection } = connectionDefinitions({
name: _.camelCase(`${type.name} groupConnection`),
nodeType: type.nodeObjectType,
connectionFields: () => {
return {
field: { type: GraphQLString },
fieldValue: { type: GraphQLString },
totalCount: { type: GraphQLInt },
}
},
})
return {
totalCount: {
type: GraphQLInt,
},
distinct: {
type: new GraphQLList(GraphQLString),
args: {
field: {
type: new GraphQLEnumType({
name: _.camelCase(`${type.name} distinct enum`),
values: enumValues,
}),
},
},
resolve(connection, args) {
let fieldName = args.field
if (_.includes(args.field, `___`)) {
fieldName = args.field.replace(`___`, `.`)
}
const fields = connection.edges.map(edge => _.get(edge.node, fieldName))
return _.sortBy(_.filter(_.uniq(_.flatten(fields)), _.identity))
},
},
group: {
type: new GraphQLList(groupConnection),
args: {
...connectionArgs,
field: {
type: new GraphQLEnumType({
name: _.camelCase(`${type.name} group enum`),
values: enumValues,
}),
},
},
resolve(connection, args) {
const fieldName = args.field.replace(`___`, `.`)
const connectionNodes = connection.edges.map(edge => edge.node)
let groups = {}
// Do a custom grouping for arrays (w/ a group per array value)
// Find the first node with this field and check if it's an array.
if (_.isArray(_.get(_.find(connectionNodes, fieldName), fieldName))) {
const values = _.uniq(
_.reduce(
connectionNodes,
(vals, n) => {
if (_.has(n, fieldName)) {
return vals.concat(_.get(n, fieldName))
} else {
return vals
}
},
[]
)
)
values.forEach(val => {
groups[val] = _.filter(connectionNodes, n =>
_.includes(_.get(n, fieldName), val)
)
})
} else {
groups = _.groupBy(connectionNodes, fieldName)
}
const groupConnections = []
// Do default sort by fieldValue
const sortedFieldValues = _.sortBy(_.keys(groups))
_.each(sortedFieldValues, fieldValue => {
const groupNodes = groups[fieldValue]
const groupConn = connectionFromArray(groupNodes, args)
groupConn.totalCount = groupNodes.length
groupConn.field = fieldName
groupConn.fieldValue = fieldValue
groupConnections.push(groupConn)
})
return groupConnections
},
},
}
}