-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
61 lines (54 loc) · 1.47 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
const fp = require('fastify-plugin')
const mercurius = require('mercurius')
const PLUGIN_NAME = 'mercuriusDynamicSchema'
const STRATEGY_NAME = 'mercuriusDynamicSchemaStrategy'
function strategyFactory({ name, strategy }) {
return {
name,
storage: function () {
const handlers = {}
return {
get: type => {
return handlers[type] || null
},
set: (type, store) => {
handlers[type] = store
}
}
},
deriveConstraint: strategy,
mustMatchWhenDerived: true
}
}
async function mercuriusDynamicSchema(fastify, opts) {
const constraintStrategy = strategyFactory({
name: STRATEGY_NAME,
strategy: opts.strategy
})
fastify.addConstraintStrategy(constraintStrategy)
const contextFn = opts.context
for (const schema of opts.schemas) {
await fastify.register(
async childServer => {
childServer.register(mercurius, {
schema: schema.schema,
path: schema.path,
resolvers: schema.resolvers,
graphiql: false,
context: contextFn,
routes: true,
additionalRouteOptions: {
constraints: { [STRATEGY_NAME]: schema.name }
}
})
},
{ name: `${PLUGIN_NAME}.${schema.name}` }
)
}
}
module.exports = fp(mercuriusDynamicSchema, {
fastify: '4.x',
name: PLUGIN_NAME
})
module.exports.default = mercuriusDynamicSchema
module.exports.mercuriusDynamicSchema = mercuriusDynamicSchema