1 | import { fetchache, Request } from 'fetchache';
|
2 | import { UrlLoader } from '@graphql-tools/url-loader';
|
3 | import { buildClientSchema, introspectionFromSchema } from 'graphql';
|
4 | import { introspectSchema } from '@graphql-tools/wrap';
|
5 | import { getInterpolatedHeadersFactory, getHeadersObject } from '@graphql-mesh/utils';
|
6 |
|
7 | class 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.cacheIntrospection) {
|
32 | const cacheKey = this.name + '_introspection';
|
33 | const introspectionData = await this.cache.get(cacheKey);
|
34 | if (introspectionData) {
|
35 | schema = buildClientSchema(introspectionData);
|
36 | }
|
37 | else {
|
38 | schema = await introspectSchema(async (params) => {
|
39 | const { executor } = await getExecutorAndSubscriberForParams(params, schemaHeadersFactory);
|
40 | return executor(params);
|
41 | });
|
42 | await this.cache.set(cacheKey, introspectionFromSchema(schema));
|
43 | }
|
44 | }
|
45 | else {
|
46 | schema = await introspectSchema(async (params) => {
|
47 | const { executor } = await getExecutorAndSubscriberForParams(params, schemaHeadersFactory);
|
48 | return executor(params);
|
49 | });
|
50 | }
|
51 | const operationHeadersFactory = getInterpolatedHeadersFactory(this.config.operationHeaders);
|
52 | return {
|
53 | schema,
|
54 | executor: async (params) => {
|
55 | const { executor } = await getExecutorAndSubscriberForParams(params, operationHeadersFactory);
|
56 | return executor(params);
|
57 | },
|
58 | subscriber: async (params) => {
|
59 | const { subscriber } = await getExecutorAndSubscriberForParams(params, operationHeadersFactory);
|
60 | return subscriber(params);
|
61 | },
|
62 | };
|
63 | }
|
64 | }
|
65 |
|
66 | export default GraphQLHandler;
|
67 |
|