-
Notifications
You must be signed in to change notification settings - Fork 1
/
index.js
97 lines (85 loc) · 2.48 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
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
import { readFileSync } from 'fs'
import fp from 'fastify-plugin'
import semver from 'semver'
import { Collector } from './lib/collector.js'
import wrapResolvers from './lib/wrapResolvers.js'
import {
DEFAULT_OPTIONS,
FEDERATION_HEADER,
kFederationHeader
} from './lib/constant.js'
import { extractExplainGateway } from './lib/gateway.js'
const fileUrl = new URL('./package.json', import.meta.url)
const packageJSON = JSON.parse(readFileSync(fileUrl))
export default fp(async (fastify, opts) => {
const options = { ...DEFAULT_OPTIONS, ...opts }
fastify.graphql.addHook('preParsing', async (schema, source, context) => {
const enabled = await isEnabled(options, {
schema,
source,
context
})
if (!enabled) {
context.explain = {
enabled
}
return
}
context.explain = {
enabled,
gateway: options.gateway,
federated: options.federated,
collector: new Collector()
}
})
fastify.graphql.addHook('onResolution', async (execution, context) => {
if (!context.explain.enabled) return
execution.extensions = formatExtensions(execution, context)
})
wrapResolvers(fastify.graphql.schema)
})
function formatExtensions(execution, context) {
const profiler = context.explain.collector.exportEntries()
const resolverCalls = context.explain.collector.exportResolversCalls()
if (context.explain.gateway) {
extractExplainGateway(context, { profiler, resolverCalls })
}
return {
...execution.extensions,
explain: {
gateway: context.explain.gateway,
version: packageJSON.version,
profiler: {
data: profiler
},
resolverCalls: {
data: resolverCalls
}
}
}
}
async function isEnabled(options, { schema, source, context }) {
if (options.federated && context.reply.request.headers[kFederationHeader]) {
return true
}
try {
return typeof options.enabled === 'function'
? await options.enabled({ schema, source, context })
: options.enabled
} catch (error) {
return false
}
}
export function getExplainFederatedHeader(context) {
if (context?.explain?.enabled) {
return FEDERATION_HEADER
}
}
export function explainGraphiQLPlugin({ version } = {}) {
const packageVersion = version || `^${semver.major(packageJSON.version)}`
return {
name: 'mercuriusExplain',
umdUrl: `https://unpkg.com/mercurius-explain-graphiql-plugin@${packageVersion}/dist/umd/index.js`,
fetcherWrapper: 'parseFetchResponse'
}
}