UNPKG

@graphql-yoga/plugin-sofa

Version:
73 lines (72 loc) 3.11 kB
import { useSofa as createSofaHandler } from 'sofa-api'; import { handleMaybePromise } from '@whatwg-node/promise-helpers'; export function useSofa(config) { let sofaHandler; let getEnveloped; const envelopedByContext = new WeakMap(); return { onYogaInit({ yoga }) { getEnveloped = yoga.getEnveloped; }, onSchemaChange(onSchemaChangeEventPayload) { sofaHandler = createSofaHandler({ ...config, schema: onSchemaChangeEventPayload.schema, context(serverContext) { const enveloped = getEnveloped(serverContext); return handleMaybePromise(() => enveloped.contextFactory(serverContext), contextValue$ => { envelopedByContext.set(contextValue$, enveloped); return contextValue$; }); }, execute(...args) { const executionArgs = args.length === 1 ? args[0] : { schema: args[0], document: args[1], rootValue: args[2], contextValue: args[3], variableValues: args[4], operationName: args[5], fieldResolver: args[6], typeResolver: args[7], }; const enveloped = envelopedByContext.get(executionArgs.contextValue); if (!enveloped) { throw new TypeError('Illegal invocation.'); } return enveloped.execute(executionArgs); }, subscribe(...args) { const subscriptionArgs = args.length === 1 ? args[0] : { schema: args[0], document: args[1], rootValue: args[2], contextValue: args[3], variableValues: args[4], operationName: args[5], fieldResolver: args[6], subscribeFieldResolver: args[7], }; const enveloped = envelopedByContext.get(subscriptionArgs.contextValue); if (!enveloped) { throw new TypeError('Illegal invocation.'); } return enveloped.subscribe(subscriptionArgs); }, }); }, onRequest({ request, endResponse, serverContext, url }) { if (url.pathname.startsWith(config.basePath)) { return handleMaybePromise(() => sofaHandler.handleRequest(request, serverContext), res => { if (res) { endResponse(res); } }); } }, }; }