This repository has been archived by the owner on Oct 30, 2023. It is now read-only.
/
introspection.js
67 lines (57 loc) · 1.74 KB
/
introspection.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
/**
* This file holds logic regarding the necessary introspection
* query made to the GraphQL endpoint to build the fragment
* matching system.
*/
import { makePromise, execute } from 'apollo-link'
import { IntrospectionFragmentMatcher } from 'apollo-cache-inmemory'
import { pipe, prop } from 'ramda'
import query from './fragment-matcher-query.gql'
/**
* Normalize introspection result to keep only needed data.
*/
const normalize = pipe(
prop('data'),
data => {
// here we're filtering out any type information unrelated to unions or interfaces
// @see: https://www.apollographql.com/docs/react/advanced/fragments.html#fragment-matcher
data.__schema.types = data.__schema.types.filter(
type => type.possibleTypes !== null
)
return data
}
)
/**
* Handle connection error to point developer to a solution.
*/
const handleConnectionError = err => {
if (err.name === 'FetchError' && err.code === 'ECONNREFUSED') {
throw new Error(
'Could not connect to GraphQL API. During development, make sure you are running it locally.'
)
}
throw err
}
// cache in-memory
let introspectionData
/**
* Imperative introspection fulfil.
*/
export const saveIntrospectionData = data => (introspectionData = data)
/**
* Performs an fragment-matcher introspection query on the provided link.
*/
export const introspectLink = link =>
introspectionData ||
makePromise(execute(link, { query }))
.then(normalize)
.then(saveIntrospectionData)
.catch(handleConnectionError)
/**
* Creates an instropection fragment matcher based on a provided
* introspection query result.
*/
export const createFragmentMatcher = introspection =>
new IntrospectionFragmentMatcher({
introspectionQueryResultData: introspection
})