Skip to content

Commit

Permalink
Enable Automatic Type Merging for relevant handlers
Browse files Browse the repository at this point in the history
  • Loading branch information
ardatan committed Sep 6, 2022
1 parent 44b8681 commit 24afabe
Show file tree
Hide file tree
Showing 8 changed files with 40 additions and 34 deletions.
8 changes: 8 additions & 0 deletions .changeset/honest-candles-act.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
---
'@graphql-mesh/mongoose': patch
'@graphql-mesh/mysql': patch
'@graphql-mesh/runtime': patch
'@graphql-mesh/types': patch
---

Enable Automatic Type Merging by default
1 change: 0 additions & 1 deletion packages/handlers/mongoose/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,6 @@
"graphql-compose-mongoose": "9.7.1",
"graphql-compose-connection": "8.2.1",
"graphql-compose-pagination": "8.3.0",
"@graphql-tools/stitching-directives": "2.3.8",
"tslib": "^2.4.0"
},
"publishConfig": {
Expand Down
42 changes: 16 additions & 26 deletions packages/handlers/mongoose/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,6 @@ import { MeshHandlerOptions, MeshPubSub, MeshHandler, MeshSource, YamlConfig, Im
import { connect, disconnect, ConnectOptions, Document, Model } from 'mongoose';
import { loadFromModuleExportExpression } from '@graphql-mesh/utils';
import { specifiedDirectives } from 'graphql';
import { stitchingDirectives } from '@graphql-tools/stitching-directives';

const modelQueryOperations = [
'findById',
Expand Down Expand Up @@ -53,6 +52,8 @@ export default class MongooseHandler implements MeshHandler {
}

const schemaComposer = new SchemaComposer();
const typeMergingOptions: MeshSource['merge'] = {};

await Promise.all([
Promise.all(
this.config.models?.map(async modelConfig => {
Expand Down Expand Up @@ -81,16 +82,13 @@ export default class MongooseHandler implements MeshHandler {
)
),
]);
if (this.config.autoTypeMerging) {
modelTC.setDirectiveByName('key', {
selectionSet: /* GraphQL */ `
{
id
}
`,
});
modelTC.setFieldDirectiveByName(`${modelConfig.name}_dataLoaderMany`, 'merge');
}
const typeName = modelTC.getTypeName();
typeMergingOptions[typeName] = {
selectionSet: `{ id }`,
key: ({ id }) => id,
argsFromKeys: ids => ({ ids }),
fieldName: `${typeName}_dataLoaderMany`,
};
}) || []
),
Promise.all(
Expand All @@ -117,28 +115,20 @@ export default class MongooseHandler implements MeshHandler {
)
),
]);
if (this.config.autoTypeMerging) {
discriminatorTC.setDirectiveByName('key', {
selectionSet: /* GraphQL */ `
{
id
}
`,
});
discriminatorTC.setFieldDirectiveByName(`${discriminatorConfig.name}_dataLoaderMany`, 'merge');
}
const typeName = discriminatorTC.getTypeName();
typeMergingOptions[typeName] = {
selectionSet: `{ id }`,
key: ({ id }) => id,
argsFromKeys: ids => ({ ids }),
fieldName: `${typeName}_dataLoaderMany`,
};
}) || []
),
]);

// graphql-compose doesn't add @defer and @stream to the schema
specifiedDirectives.forEach(directive => schemaComposer.addDirective(directive));

if (this.config.autoTypeMerging) {
const defaultStitchingDirectives = stitchingDirectives();
defaultStitchingDirectives.allStitchingDirectives.forEach(directive => schemaComposer.addDirective(directive));
}

const schema = schemaComposer.buildSchema();

return {
Expand Down
4 changes: 0 additions & 4 deletions packages/handlers/mongoose/yaml-config.graphql
Original file line number Diff line number Diff line change
Expand Up @@ -6,10 +6,6 @@ type MongooseHandler @md {
connectionString: String
models: [MongooseModel]
discriminators: [MongooseModel]
"""
Enable Automatic Type Merging/Federation support
"""
autoTypeMerging: Boolean
}

type MongooseModel {
Expand Down
14 changes: 14 additions & 0 deletions packages/handlers/mysql/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -216,6 +216,7 @@ export default class MySQLHandler implements MeshHandler {
});
const tables = await introspectionConnection.getDatabaseTables(pool.config.connectionConfig.database);
const tableNames = this.config.tables || Object.keys(tables);
const typeMergingOptions: MeshSource['merge'] = {};
await Promise.all(
tableNames.map(async tableName => {
if (this.config.tables && !this.config.tables.includes(tableName)) {
Expand Down Expand Up @@ -429,6 +430,19 @@ export default class MySQLHandler implements MeshHandler {
});
})
);
typeMergingOptions[objectTypeName] = {
selectionSet: `{ ${[...primaryKeys].join(' ')} }`,
args: obj => {
const where = {};
for (const primaryKey of primaryKeys) {
where[primaryKey] = obj[primaryKey];
}
return {
where,
};
},
valuesFromResults: results => results[0],
};
schemaComposer.Query.addFields({
[tableName]: {
type: '[' + objectTypeName + ']',
Expand Down
2 changes: 1 addition & 1 deletion packages/runtime/src/get-mesh.ts
Original file line number Diff line number Diff line change
Expand Up @@ -193,7 +193,7 @@ export async function getMesh(options: GetMeshOptions): Promise<MeshInstance> {
contextVariables: source.contextVariables || {},
handler: apiSource.handler,
batch: 'batch' in source ? source.batch : true,
merge: apiSource.merge,
merge: source.merge,
createProxyingResolver: createProxyingResolverFactory(apiName),
});
} catch (e: any) {
Expand Down
2 changes: 0 additions & 2 deletions packages/runtime/src/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,6 @@ import {
import { DocumentNode, ExecutionResult } from 'graphql';
import { IResolvers, Source } from '@graphql-tools/utils';
import { MESH_CONTEXT_SYMBOL } from './constants';
import { MergedTypeConfig } from '@graphql-tools/delegate';
import { MeshInstance } from './get-mesh';
import { envelop } from '@envelop/core';

Expand All @@ -35,7 +34,6 @@ export type MeshResolvedSource = {
name: string;
handler: MeshHandler;
transforms?: MeshTransform[];
merge?: Record<string, MergedTypeConfig>;
};

export type ExecuteMeshFn<TData = any, TVariables = any, TContext = any, TRootValue = any> = (
Expand Down
1 change: 1 addition & 0 deletions packages/types/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@ export type MeshSource = {
executor?: Executor;
contextVariables?: Record<string, string>;
batch?: boolean;
merge?: Record<string, MergedTypeConfig>;
};

export interface KeyValueCacheSetOptions {
Expand Down

0 comments on commit 24afabe

Please sign in to comment.