UNPKG

graphql-modules

Version:

Create reusable, maintainable, testable and extendable GraphQL modules

55 lines (54 loc) 2.42 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.subscriptionCreator = subscriptionCreator; const graphql_1 = require("graphql"); const utils_1 = require("../shared/utils"); function subscriptionCreator({ contextBuilder, }) { const createSubscription = (options) => { // Custom or original subscribe function const subscribeFn = (options === null || options === void 0 ? void 0 : options.subscribe) || graphql_1.subscribe; return (argsOrSchema, document, rootValue, contextValue, variableValues, operationName, fieldResolver, subscribeFieldResolver) => { function perform({ context, ɵdestroy: destroy, }) { const subscriptionArgs = (0, utils_1.isNotSchema)(argsOrSchema) ? { ...argsOrSchema, contextValue: context, } : { schema: argsOrSchema, document: document, rootValue, contextValue: context, variableValues, operationName, fieldResolver, subscribeFieldResolver, }; let isIterable = false; // It's important to wrap the subscribeFn within a promise // so we can easily control the end of subscription (with finally) return Promise.resolve() .then(() => subscribeFn(subscriptionArgs)) .then((sub) => { if ((0, utils_1.isAsyncIterable)(sub)) { isIterable = true; return (0, utils_1.tapAsyncIterator)(sub, destroy); } return sub; }) .finally(() => { if (!isIterable) { destroy(); } }); } if (options === null || options === void 0 ? void 0 : options.controller) { return perform(options.controller); } return contextBuilder((0, utils_1.isNotSchema)(argsOrSchema) ? argsOrSchema.contextValue : contextValue).runWithContext(perform); }; }; return createSubscription; }