UNPKG

@graphql-yoga/plugin-sofa

Version:
76 lines (75 loc) 3.24 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.useSofa = useSofa; const sofa_api_1 = require("sofa-api"); const promise_helpers_1 = require("@whatwg-node/promise-helpers"); function useSofa(config) { let sofaHandler; let getEnveloped; const envelopedByContext = new WeakMap(); return { onYogaInit({ yoga }) { getEnveloped = yoga.getEnveloped; }, onSchemaChange(onSchemaChangeEventPayload) { sofaHandler = (0, sofa_api_1.useSofa)({ ...config, schema: onSchemaChangeEventPayload.schema, context(serverContext) { const enveloped = getEnveloped(serverContext); return (0, promise_helpers_1.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 (0, promise_helpers_1.handleMaybePromise)(() => sofaHandler.handleRequest(request, serverContext), res => { if (res) { endResponse(res); } }); } }, }; }