UNPKG

@gqlts/runtime

Version:

Gqlts runtime client

93 lines 3.6 kB
import { createClient as createWSClient, } from 'graphql-ws'; import { Observable } from 'zen-observable-ts'; import { createFetcher } from '../fetcher'; import { generateGraphqlOperation } from './generateGraphqlOperation'; export function createClient({ queryRoot, mutationRoot, subscriptionRoot, generateGraphqlOperationOptions, ...options }) { const { fetcherMethod, fetcherInstance } = createFetcher(options); const client = { fetcherInstance, fetcherMethod, }; if (queryRoot) { client.query = (request, config) => { if (!queryRoot) throw new Error('queryRoot argument is missing'); return client.fetcherMethod(generateGraphqlOperation('query', queryRoot, request, generateGraphqlOperationOptions), config); }; } if (mutationRoot) { client.mutation = (request, config) => { if (!mutationRoot) throw new Error('mutationRoot argument is missing'); return client.fetcherMethod(generateGraphqlOperation('mutation', mutationRoot, request, generateGraphqlOperationOptions), config); }; } if (subscriptionRoot) { client.subscription = (request, config) => { if (!subscriptionRoot) { throw new Error('subscriptionRoot argument is missing'); } const op = generateGraphqlOperation('subscription', subscriptionRoot, request, generateGraphqlOperationOptions); if (!client.wsClient) { client.wsClient = getSubscriptionClient(options, config); } return new Observable((observer) => { const unsubscribe = client.wsClient?.subscribe(op, { next: (data) => observer.next(data), error: (err) => observer.error(err), complete: () => observer.complete(), }); return () => { unsubscribe?.(); }; }); }; } return client; } function getSubscriptionClient(opts = {}, config) { const { url: httpClientUrl, subscription, webSocketImpl } = opts || {}; let { url, headers = {}, ...restOpts } = subscription || {}; // by default use the top level url if (!url && httpClientUrl) { url = httpClientUrl?.replace(/^http/, 'ws'); } if (!url) { throw new Error('Subscription client error: missing url parameter'); } const explicitWebSocketImpl = getExplicitWebSocketImpl(config?.webSocketImpl ?? restOpts.webSocketImpl ?? webSocketImpl); const wsOpts = { url, lazy: true, shouldRetry: () => true, retryAttempts: 3, connectionParams: async () => { let headersObject = typeof headers == 'function' ? await headers() : headers; headersObject = headersObject || {}; return { headers: headersObject, }; }, ...restOpts, ...config, }; if (explicitWebSocketImpl) { wsOpts.webSocketImpl = explicitWebSocketImpl; } return createWSClient(wsOpts); } function getExplicitWebSocketImpl(webSocketImpl) { if (!webSocketImpl) { return undefined; } if (typeof webSocketImpl === 'function' && 'constructor' in webSocketImpl && 'CLOSED' in webSocketImpl && 'CLOSING' in webSocketImpl && 'CONNECTING' in webSocketImpl && 'OPEN' in webSocketImpl) { return webSocketImpl; } return undefined; } //# sourceMappingURL=createClient.js.map