@envelop/execute-subscription-event
Version:
53 lines (52 loc) • 2.83 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
exports.subscribe = void 0;
const tslib_1 = require("tslib");
const graphql_1 = require("graphql");
const core_1 = require("@envelop/core");
const promise_helpers_1 = require("@whatwg-node/promise-helpers");
const validateSubscriptionArgsPromise = Promise.resolve().then(() => tslib_1.__importStar(require('graphql'))).then(graphqlModule => graphqlModule
.validateSubscriptionArgs);
function getSourceEventStream(args, validateSubscriptionArgs) {
if (validateSubscriptionArgs) {
const validatedArgs = validateSubscriptionArgs(args);
if (!('schema' in validatedArgs)) {
return { errors: validatedArgs };
}
// Cast away the installed graphql version's own overloads here for backwards compatability
const createSourceEventStreamWithValidatedArgs = graphql_1.createSourceEventStream;
return createSourceEventStreamWithValidatedArgs(validatedArgs);
}
const legacyCreateSourceEventStream = graphql_1.createSourceEventStream;
return legacyCreateSourceEventStream(args.schema, args.document, args.rootValue, args.contextValue, args.variableValues ?? undefined, args.operationName, args.subscribeFieldResolver);
}
/**
* This is a almost identical port from graphql-js subscribe.
* The only difference is that a custom `execute` function can be injected for customizing the behavior.
*/
const subscribe = (execute) => (0, core_1.makeSubscribe)(args => {
const { schema, document, contextValue, variableValues, operationName, fieldResolver } = args;
return (0, promise_helpers_1.handleMaybePromise)(() => validateSubscriptionArgsPromise, (validateSubscriptionArgs) => (0, promise_helpers_1.handleMaybePromise)(() => getSourceEventStream(args, validateSubscriptionArgs), (resultOrStream) => {
if (!(0, core_1.isAsyncIterable)(resultOrStream)) {
return resultOrStream;
}
// Map every source value to a ExecutionResult value as described above.
return (0, core_1.mapAsyncIterator)(resultOrStream,
// For each payload yielded from a subscription, map it over the normal
// GraphQL `execute` function, with `payload` as the rootValue.
// This implements the "MapSourceToResponseEvent" algorithm described in
// the GraphQL specification. The `execute` function provides the
// "ExecuteSubscriptionEvent" algorithm, as it is nearly identical to the
// "ExecuteQuery" algorithm, for which `execute` is also used.
(payload) => execute({
schema,
document,
rootValue: payload,
contextValue,
variableValues,
operationName,
fieldResolver,
}));
}));
});
exports.subscribe = subscribe;