Skip to content

Commit

Permalink
New onFetch hook (#4404)
Browse files Browse the repository at this point in the history
* New \onFetch` hook

* Go

* chore(dependencies): updated changesets for modified dependencies

Co-authored-by: github-actions[bot] <github-actions[bot]@users.noreply.github.com>
  • Loading branch information
ardatan and github-actions[bot] authored Aug 31, 2022
1 parent a0872d4 commit d879077
Show file tree
Hide file tree
Showing 38 changed files with 601 additions and 387 deletions.
7 changes: 7 additions & 0 deletions .changeset/@graphql-mesh_config-4404-dependencies.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
---
"@graphql-mesh/config": patch
---

dependencies updates:

- Added dependency [`@whatwg-node/[email protected]` ↗︎](https://www.npmjs.com/package/@whatwg-node/fetch/v/0.3.2) (to `dependencies`)
8 changes: 8 additions & 0 deletions .changeset/@graphql-mesh_runtime-4404-dependencies.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
---
"@graphql-mesh/runtime": patch
---

dependencies updates:

- Added dependency [`[email protected]` ↗︎](https://www.npmjs.com/package/fetchache/v/0.1.2) (to `dependencies`)
- Added dependency [`@whatwg-node/[email protected]` ↗︎](https://www.npmjs.com/package/@whatwg-node/fetch/v/0.3.2) (to `dependencies`)
22 changes: 22 additions & 0 deletions .changeset/old-mangos-dream.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
---
'@graphql-mesh/config': minor
'@graphql-mesh/graphql': minor
'@graphql-mesh/grpc': minor
'@graphql-mesh/json-schema': minor
'@graphql-mesh/mongoose': minor
'@graphql-mesh/mysql': minor
'@graphql-mesh/neo4j': minor
'@graphql-mesh/odata': minor
'@graphql-mesh/openapi': minor
'@graphql-mesh/postgraphile': minor
'@graphql-mesh/raml': minor
'@graphql-mesh/soap': minor
'@graphql-mesh/thrift': minor
'@graphql-mesh/tuql': minor
'@omnigraph/json-schema': minor
'@graphql-mesh/runtime': minor
'@graphql-mesh/types': minor
'@graphql-mesh/utils': minor
---

New `onFetch` hook!
1 change: 1 addition & 0 deletions packages/config/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,7 @@
"@graphql-tools/load": "7.7.5",
"@graphql-tools/code-file-loader": "7.3.4",
"@graphql-tools/graphql-file-loader": "7.5.3",
"@whatwg-node/fetch": "0.3.2",
"param-case": "3.0.4",
"@envelop/core": "2.5.0",
"tslib": "^2.4.0",
Expand Down
29 changes: 6 additions & 23 deletions packages/config/src/process.ts
Original file line number Diff line number Diff line change
@@ -1,19 +1,14 @@
import { path as pathModule, process } from '@graphql-mesh/cross-helpers';
import type { MeshResolvedSource } from '@graphql-mesh/runtime';
import type { GetMeshOptions, MeshResolvedSource } from '@graphql-mesh/runtime';
import {
ImportFn,
Logger,
MeshHandlerLibrary,
MeshMerger,
MeshMergerLibrary,
MeshPluginFactory,
MeshPubSub,
MeshTransform,
MeshTransformLibrary,
YamlConfig,
KeyValueCache,
} from '@graphql-mesh/types';
import { IResolvers, Source } from '@graphql-tools/utils';
import { Source } from '@graphql-tools/utils';
import { concatAST, DocumentNode, parse, print, visit } from 'graphql';
import {
getPackage,
Expand All @@ -28,7 +23,7 @@ import { FsStoreStorageAdapter, MeshStore, InMemoryStoreStorageAdapter } from '@
import { pascalCase } from 'pascal-case';
import { camelCase } from 'camel-case';
import { defaultImportFn, parseWithCache, resolveAdditionalResolvers } from '@graphql-mesh/utils';
import { envelop, useMaskedErrors, useImmediateIntrospection } from '@envelop/core';
import { useMaskedErrors, useImmediateIntrospection } from '@envelop/core';
import { getAdditionalResolversFromTypeDefs } from './getAdditionalResolversFromTypeDefs';

const ENVELOP_CORE_PLUGINS_MAP = {
Expand Down Expand Up @@ -57,24 +52,12 @@ export type ConfigProcessOptions = {
throwOnInvalidConfig?: boolean;
};

type EnvelopPlugins = Parameters<typeof envelop>[0]['plugins'];

export type ProcessedConfig = {
sources: MeshResolvedSource[];
transforms: MeshTransform[];
additionalTypeDefs: DocumentNode[];
additionalResolvers: IResolvers[];
cache: KeyValueCache<string>;
merger: MeshMerger;
pubsub: MeshPubSub;
export type ProcessedConfig = GetMeshOptions & {
config: YamlConfig.Config;
documents: Source[];
logger: Logger;
store: MeshStore;
importCodes: string[];
codes: string[];
additionalEnvelopPlugins: EnvelopPlugins;
includeHttpDetailsInExtensions: boolean;
};

function getDefaultMeshStore(dir: string, importFn: ImportFn, artifactsDir: string) {
Expand Down Expand Up @@ -208,7 +191,6 @@ export async function processConfig(
store: sourcesStore.child(${JSON.stringify(source.name)}),
logger: logger.child(${JSON.stringify(source.name)}),
importFn,
fetchFn,
});`);
}
return new HandlerCtor({
Expand All @@ -220,7 +202,6 @@ export async function processConfig(
store: sourcesStore.child(source.name),
logger: logger.child(source.name),
importFn,
fetchFn,
});
}),
Promise.all(
Expand Down Expand Up @@ -594,6 +575,7 @@ export async function processConfig(
.join(',')}
];
},
fetchFn,
};
}`);
}
Expand All @@ -613,5 +595,6 @@ export async function processConfig(
includeHttpDetailsInExtensions: config.includeHttpDetailsInExtensions,
importCodes,
codes,
fetchFn,
};
}
11 changes: 6 additions & 5 deletions packages/config/src/utils.ts
Original file line number Diff line number Diff line change
@@ -1,10 +1,11 @@
import { KeyValueCache, YamlConfig, ImportFn, MeshPubSub, Logger } from '@graphql-mesh/types';
import { KeyValueCache, YamlConfig, ImportFn, MeshPubSub, Logger, MeshFetch } from '@graphql-mesh/types';
import { path } from '@graphql-mesh/cross-helpers';
import { printSchemaWithDirectives, Source } from '@graphql-tools/utils';
import { paramCase } from 'param-case';
import { loadDocuments, loadTypedefs } from '@graphql-tools/load';
import { GraphQLFileLoader } from '@graphql-tools/graphql-file-loader';
import { PubSub, DefaultLogger, parseWithCache, createDefaultMeshFetch, MeshFetch } from '@graphql-mesh/utils';
import { PubSub, DefaultLogger, parseWithCache } from '@graphql-mesh/utils';
import { fetch as defaultFetch } from '@whatwg-node/fetch';
import { CodeFileLoader } from '@graphql-tools/code-file-loader';
import { MeshStore } from '@graphql-mesh/store';

Expand Down Expand Up @@ -101,11 +102,11 @@ export async function resolveCustomFetch({
}> {
let importCode = '';
if (!fetchConfig) {
importCode += `import { createDefaultMeshFetch } from '@graphql-mesh/utils';\n`;
importCode += `import { fetch as fetchFn } from '@whatwg-node/fetch';\n`;
return {
fetchFn: createDefaultMeshFetch(cache),
fetchFn: defaultFetch,
importCode,
code: `const fetchFn = createDefaultMeshFetch(cache);`,
code: ``,
};
}
const { moduleName, resolved: fetchFn } = await getPackage<MeshFetch>({
Expand Down
27 changes: 14 additions & 13 deletions packages/handlers/graphql/src/index.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,13 @@
import { GetMeshSourceOptions, MeshHandler, MeshSource, YamlConfig, ImportFn, Logger } from '@graphql-mesh/types';
import {
MeshHandlerOptions,
MeshHandler,
MeshSource,
YamlConfig,
ImportFn,
Logger,
MeshFetch,
GetMeshSourcePayload,
} from '@graphql-mesh/types';
import { UrlLoader, SubscriptionProtocol } from '@graphql-tools/url-loader';
import {
GraphQLSchema,
Expand All @@ -13,7 +22,7 @@ import {
GraphQLResolveInfo,
} from 'graphql';
import { introspectSchema } from '@graphql-tools/wrap';
import { loadFromModuleExportExpression, MeshFetch, readFileOrUrl } from '@graphql-mesh/utils';
import { loadFromModuleExportExpression, readFileOrUrl } from '@graphql-mesh/utils';
import {
ExecutionRequest,
isDocumentNode,
Expand Down Expand Up @@ -51,19 +60,10 @@ export default class GraphQLHandler implements MeshHandler {
private logger: Logger;
private urlLoader = new UrlLoader();

constructor({
name,
config,
baseDir,
fetchFn,
store,
importFn,
logger,
}: GetMeshSourceOptions<YamlConfig.Handler['graphql']>) {
constructor({ name, config, baseDir, store, importFn, logger }: MeshHandlerOptions<YamlConfig.Handler['graphql']>) {
this.name = name;
this.config = config;
this.baseDir = baseDir;
this.fetchFn = fetchFn;
this.nonExecutableSchema = store.proxy('introspectionSchema', PredefinedProxyOptions.GraphQLSchemaWithDiffing);
this.importFn = importFn;
this.logger = logger;
Expand Down Expand Up @@ -247,7 +247,8 @@ export default class GraphQLHandler implements MeshHandler {
};
}

async getMeshSource(): Promise<MeshSource> {
async getMeshSource({ fetchFn }: GetMeshSourcePayload): Promise<MeshSource> {
this.fetchFn = fetchFn;
if ('sources' in this.config) {
if (this.config.strategy === 'race') {
const schemaPromises: Promise<GraphQLSchema>[] = [];
Expand Down
19 changes: 15 additions & 4 deletions packages/handlers/graphql/test/handler.spec.ts
Original file line number Diff line number Diff line change
@@ -1,10 +1,13 @@
/* eslint-disable import/no-extraneous-dependencies */
/* eslint-disable import/no-nodejs-modules */
import InMemoryLRUCache from '@graphql-mesh/cache-localforage';
import GraphQLHandler from '../src';
import { PubSub, defaultImportFn, DefaultLogger } from '@graphql-mesh/utils';
import { promises as fsPromises } from 'fs';
import { join } from 'path';
import { buildASTSchema, buildSchema, introspectionFromSchema } from 'graphql';
import { InMemoryStoreStorageAdapter, MeshStore } from '@graphql-mesh/store';
import { fetch as fetchFn } from '@whatwg-node/fetch';

const { readFile } = fsPromises;

Expand Down Expand Up @@ -32,7 +35,9 @@ describe('graphql', () => {
const absoluteFilePath = join(__dirname, sdlFilePath);
const schemaStringFromFile = await readFile(absoluteFilePath, 'utf-8');
const schemaFromFile = buildSchema(schemaStringFromFile);
const { schema: schemaFromHandler } = await handler.getMeshSource();
const { schema: schemaFromHandler } = await handler.getMeshSource({
fetchFn,
});
expect(introspectionFromSchema(schemaFromHandler)).toStrictEqual(introspectionFromSchema(schemaFromFile));
});
it('handle code files exports GraphQLSchema correctly', async () => {
Expand All @@ -55,7 +60,9 @@ describe('graphql', () => {
});
const absoluteFilePath = join(__dirname, schemaFilePath);
const schemaFromFile = require(absoluteFilePath);
const { schema: schemaFromHandler } = await handler.getMeshSource();
const { schema: schemaFromHandler } = await handler.getMeshSource({
fetchFn,
});
expect(introspectionFromSchema(schemaFromHandler)).toStrictEqual(introspectionFromSchema(schemaFromFile));
});
it('handle code files exports DocumentNode correctly', async () => {
Expand All @@ -79,7 +86,9 @@ describe('graphql', () => {
const absoluteFilePath = join(__dirname, schemaFilePath);
const schemaDocumentFromFile = require(absoluteFilePath);
const schemaFromFile = buildASTSchema(schemaDocumentFromFile);
const { schema: schemaFromHandler } = await handler.getMeshSource();
const { schema: schemaFromHandler } = await handler.getMeshSource({
fetchFn,
});
expect(introspectionFromSchema(schemaFromHandler)).toStrictEqual(introspectionFromSchema(schemaFromFile));
});
it('handle code files exports string correctly', async () => {
Expand All @@ -103,7 +112,9 @@ describe('graphql', () => {
const absoluteFilePath = join(__dirname, schemaFilePath);
const schemaStringFromFile = require(absoluteFilePath);
const schemaFromFile = buildSchema(schemaStringFromFile);
const { schema: schemaFromHandler } = await handler.getMeshSource();
const { schema: schemaFromHandler } = await handler.getMeshSource({
fetchFn,
});
expect(introspectionFromSchema(schemaFromHandler)).toStrictEqual(introspectionFromSchema(schemaFromFile));
});
});
4 changes: 2 additions & 2 deletions packages/handlers/grpc/src/index.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
/* eslint-disable import/no-duplicates */
import './patchLongJs';
import { GetMeshSourceOptions, Logger, MeshHandler, YamlConfig } from '@graphql-mesh/types';
import { MeshHandlerOptions, Logger, MeshHandler, YamlConfig } from '@graphql-mesh/types';
import { stringInterpolator } from '@graphql-mesh/string-interpolation';
import { ChannelCredentials, credentials, loadPackageDefinition } from '@grpc/grpc-js';
import { loadFileDescriptorSetFromObject } from '@grpc/proto-loader';
Expand Down Expand Up @@ -44,7 +44,7 @@ export default class GrpcHandler implements MeshHandler {
private rootJsonAndDecodedDescriptorSets: StoreProxy<RootJsonAndDecodedDescriptorSet[]>;
private logger: Logger;

constructor({ config, baseDir, store, logger }: GetMeshSourceOptions<YamlConfig.GrpcHandler>) {
constructor({ config, baseDir, store, logger }: MeshHandlerOptions<YamlConfig.GrpcHandler>) {
this.logger = logger;
this.config = config;
this.baseDir = baseDir;
Expand Down
21 changes: 15 additions & 6 deletions packages/handlers/json-schema/src/index.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,17 @@
import { PredefinedProxyOptions, StoreProxy } from '@graphql-mesh/store';
import { GetMeshSourceOptions, ImportFn, Logger, MeshHandler, MeshPubSub, YamlConfig } from '@graphql-mesh/types';
import {
MeshHandlerOptions,
ImportFn,
Logger,
MeshHandler,
MeshPubSub,
YamlConfig,
GetMeshSourcePayload,
MeshSource,
MeshFetch,
} from '@graphql-mesh/types';
import { JSONSchemaLoaderBundle, createBundle, getGraphQLSchemaFromBundle } from '@omnigraph/json-schema';
import { loadFromModuleExportExpression, MeshFetch, readFileOrUrl } from '@graphql-mesh/utils';
import { loadFromModuleExportExpression, readFileOrUrl } from '@graphql-mesh/utils';
import { getInterpolatedHeadersFactory } from '@graphql-mesh/string-interpolation';
import { process } from '@graphql-mesh/cross-helpers';

Expand All @@ -23,12 +33,10 @@ export default class JsonSchemaHandler implements MeshHandler {
pubsub,
logger,
importFn,
fetchFn,
}: GetMeshSourceOptions<YamlConfig.Handler['jsonSchema']>) {
}: MeshHandlerOptions<YamlConfig.Handler['jsonSchema']>) {
this.name = name;
this.config = config;
this.baseDir = baseDir;
this.fetchFn = fetchFn;
this.importFn = importFn;
this.bundleStoreProxy = store.proxy('jsonSchemaBundle', PredefinedProxyOptions.JsonWithoutValidation);
this.pubsub = pubsub;
Expand Down Expand Up @@ -64,7 +72,8 @@ export default class JsonSchemaHandler implements MeshHandler {
}
}

async getMeshSource() {
async getMeshSource({ fetchFn }: GetMeshSourcePayload): Promise<MeshSource> {
this.fetchFn = fetchFn;
const bundle = await this.getDereferencedBundle();
const operationHeadersConfig =
typeof this.config.operationHeaders === 'string'
Expand Down
6 changes: 4 additions & 2 deletions packages/handlers/json-schema/test/handler.spec.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
/* eslint-disable import/no-extraneous-dependencies */
import { InMemoryStoreStorageAdapter, MeshStore } from '@graphql-mesh/store';
import { defaultImportFn, DefaultLogger, getHeadersObj, PubSub } from '@graphql-mesh/utils';
import { execute, parse } from 'graphql';
Expand Down Expand Up @@ -38,6 +39,9 @@ describe('JSON Schema Handler', () => {
pubsub: new PubSub(),
logger: new DefaultLogger('test'),
importFn: defaultImportFn,
});

const { schema } = await handler.getMeshSource({
async fetchFn(info: RequestInfo, init?: RequestInit) {
const headers = typeof info === 'string' ? init?.headers : info.headers;
const headersObj = getHeadersObj(new Headers(headers || {}));
Expand All @@ -49,8 +53,6 @@ describe('JSON Schema Handler', () => {
},
});

const { schema } = await handler.getMeshSource();

const query = /* GraphQL */ `
query Test {
test {
Expand Down
4 changes: 2 additions & 2 deletions packages/handlers/mongoose/src/index.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import { composeWithMongoose, composeWithMongooseDiscriminators } from 'graphql-compose-mongoose';
import { SchemaComposer } from 'graphql-compose';
import { GetMeshSourceOptions, MeshPubSub, MeshHandler, MeshSource, YamlConfig, ImportFn } from '@graphql-mesh/types';
import { MeshHandlerOptions, MeshPubSub, MeshHandler, MeshSource, YamlConfig, ImportFn } from '@graphql-mesh/types';
import { connect, disconnect, ConnectOptions, Document, Model } from 'mongoose';
import { loadFromModuleExportExpression } from '@graphql-mesh/utils';
import { specifiedDirectives } from 'graphql';
Expand Down Expand Up @@ -35,7 +35,7 @@ export default class MongooseHandler implements MeshHandler {
private pubsub: MeshPubSub;
private importFn: ImportFn;

constructor({ config, baseDir, pubsub, importFn }: GetMeshSourceOptions<YamlConfig.MongooseHandler>) {
constructor({ config, baseDir, pubsub, importFn }: MeshHandlerOptions<YamlConfig.MongooseHandler>) {
this.config = config;
this.baseDir = baseDir;
this.pubsub = pubsub;
Expand Down
Loading

1 comment on commit d879077

@vercel
Copy link

@vercel vercel bot commented on d879077 Aug 31, 2022

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Please sign in to comment.