/
fragment-helper.js
56 lines (44 loc) · 1.48 KB
/
fragment-helper.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 Relay from 'react-relay'
export class ConnectionHelper {
constructor (selection, metadata) {
Object.keys(selection).forEach(k => (this[k] = selection[k]))
Object.keys(metadata).forEach(k => (this[k] = metadata[k]))
}
getEdge = _ => (_ = this.selections.find(_ => _.concreteType.match(/Edge$/)))
getEdgeType = _ => (_ = this.getEdge()) && _.concreteType
getEdgeNodeType = _ =>
(_ = this.getEdge()) &&
(_ = _.selections.find(_ => _.name === 'node')) &&
_.concreteType
get key () {
return this.name.replace(/^__/g, '').replace(/_connection$/g, '')
}
}
export class FragmentHelper {
constructor (schema) {
const { selections, metadata } = schema.data()
this.schema = schema
this.selections = selections
this.metadata = metadata
}
createContainer = component =>
Relay.createFragmentContainer(component, this.schema)
getSelection = alias => this.selections.find(_ => _.alias === alias)
getConnection = (alias, _) => {
return alias == null
? this.getDefaultConnection()
: (_ = this.getSelection(alias)) &&
_.concreteType.match(/Connection$/g) &&
new ConnectionHelper(
_,
this.metadata.connection.find(_ => _.path.some(_ => _ === alias))
)
}
getDefaultConnection = _ => {
return (
(_ = this.selections.find(_ => _.concreteType.match(/Connection$/g))) &&
new ConnectionHelper(_, this.metadata.connection[0])
)
}
}
export default FragmentHelper