UNPKG

3.35 kBJavaScriptView Raw
1import { fetchache, Request } from 'fetchache';
2import { UrlLoader } from '@graphql-tools/url-loader';
3import { buildClientSchema, introspectionFromSchema } from 'graphql';
4import { introspectSchema } from '@graphql-tools/wrap';
5import { getInterpolatedHeadersFactory, getHeadersObject } from '@graphql-mesh/utils';
6
7class GraphQLHandler {
8 constructor({ name, config, cache }) {
9 this.name = name;
10 this.config = config;
11 this.cache = cache;
12 }
13 async getMeshSource() {
14 const urlLoader = new UrlLoader();
15 const customFetch = (...args) => fetchache(args[0] instanceof Request ? args[0] : new Request(...args), this.cache);
16 const getExecutorAndSubscriberForParams = (params, headersFactory) => {
17 const resolverData = {
18 root: {},
19 args: params.variables,
20 context: params.context,
21 };
22 const headers = getHeadersObject(headersFactory(resolverData));
23 return urlLoader.getExecutorAndSubscriber(this.config.endpoint, {
24 customFetch: customFetch,
25 ...this.config,
26 headers,
27 });
28 };
29 let schema;
30 const schemaHeadersFactory = getInterpolatedHeadersFactory(this.config.schemaHeaders);
31 if (this.config.introspection) {
32 const result = await urlLoader.handleSDL(this.config.introspection, {
33 customFetch: customFetch,
34 ...this.config,
35 headers: this.config.schemaHeaders,
36 });
37 schema = result.schema;
38 }
39 else if (this.config.cacheIntrospection) {
40 const cacheKey = this.name + '_introspection';
41 const introspectionData = await this.cache.get(cacheKey);
42 if (introspectionData) {
43 schema = buildClientSchema(introspectionData);
44 }
45 else {
46 schema = await introspectSchema(async (params) => {
47 const { executor } = await getExecutorAndSubscriberForParams(params, schemaHeadersFactory);
48 return executor(params);
49 });
50 const ttl = typeof this.config.cacheIntrospection === 'object' && this.config.cacheIntrospection.ttl;
51 const introspection = introspectionFromSchema(schema);
52 this.cache.set(cacheKey, introspection, { ttl });
53 }
54 }
55 else {
56 schema = await introspectSchema(async (params) => {
57 const { executor } = await getExecutorAndSubscriberForParams(params, schemaHeadersFactory);
58 return executor(params);
59 });
60 }
61 const operationHeadersFactory = getInterpolatedHeadersFactory(this.config.operationHeaders);
62 return {
63 schema,
64 executor: async (params) => {
65 const { executor } = await getExecutorAndSubscriberForParams(params, operationHeadersFactory);
66 return executor(params);
67 },
68 subscriber: async (params) => {
69 const { subscriber } = await getExecutorAndSubscriberForParams(params, operationHeadersFactory);
70 return subscriber(params);
71 },
72 };
73 }
74}
75
76export default GraphQLHandler;
77//# sourceMappingURL=index.esm.js.map