UNPKG

@graphql-yoga/plugin-sofa

Version:
71 lines (70 loc) 3.06 kB
import { useSofa as createSofaHandler } from 'sofa-api'; export function useSofa(config) { let sofaHandler; let getEnveloped; const envelopedByContext = new WeakMap(); const requestByContext = new WeakMap(); return { onYogaInit({ yoga }) { getEnveloped = yoga.getEnveloped; }, onSchemaChange(onSchemaChangeEventPayload) { sofaHandler = createSofaHandler({ ...config, schema: onSchemaChangeEventPayload.schema, async context(serverContext) { const enveloped = getEnveloped(serverContext); const request = requestByContext.get(serverContext); const contextValue = await enveloped.contextFactory({ request }); 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); }, }); }, async onRequest({ request, serverContext, endResponse }) { requestByContext.set(serverContext, request); const response = await sofaHandler.handle(request, serverContext); if (response != null && response.status !== 404) { endResponse(response); } }, }; }