@graphql-mesh/transport-rest
Version:
28 lines (27 loc) • 1.69 kB
JavaScript
import { stringInterpolator } from '@graphql-mesh/string-interpolation';
import { createGraphQLError } from '@graphql-tools/utils';
export function processPubSubOperationAnnotations({ field, globalPubsub, pubsubTopic, logger: globalLogger, }) {
field.subscribe = function pubSubSubscribeFn(root, args, context, info) {
const logger = context?.logger || globalLogger;
const operationLogger = logger.child(`${info.parentType.name}.${field.name}`);
const pubsub = context?.pubsub || globalPubsub;
if (!pubsub) {
return createGraphQLError(`You should have PubSub defined in either the config or the context!`);
}
const interpolationData = { root, args, context, info, env: process.env };
let interpolatedPubSubTopic = stringInterpolator.parse(pubsubTopic, interpolationData);
if (interpolatedPubSubTopic.startsWith('webhook:')) {
const [, expectedMethod, expectedUrl] = interpolatedPubSubTopic.split(':');
const expectedPath = new URL(expectedUrl, 'http://localhost').pathname;
interpolatedPubSubTopic = `webhook:${expectedMethod}:${expectedPath}`;
}
operationLogger.debug(`${info.parentType.name}.${field.name} => Subscribing to pubSubTopic: ${interpolatedPubSubTopic}`);
return pubsub.asyncIterator(interpolatedPubSubTopic);
};
field.resolve = function pubSubResolver(root, args, context, info) {
const logger = context?.logger || globalLogger;
const operationLogger = logger.child(`${info.parentType.name}.${field.name}`);
operationLogger.debug('Received ', root, ' from ', pubsubTopic);
return root;
};
}