UNPKG

@graphql-yoga/plugin-sofa

Version:
47 lines (46 loc) 1.91 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 enveloped = envelopedByContext.get(args.contextValue); if (!enveloped) { throw new TypeError('Illegal invocation.'); } return enveloped.execute(args); }, subscribe(args) { const enveloped = envelopedByContext.get(args.contextValue); if (!enveloped) { throw new TypeError('Illegal invocation.'); } return enveloped.subscribe(args); }, }); }, async onRequest({ request, serverContext, endResponse }) { requestByContext.set(serverContext, request); const response = await sofaHandler.handle(request, serverContext); if (response != null && response.status !== 404) { endResponse(response); } }, }; }