Can two GraphQLSchema instances be merged?

1.4k Views Asked by At

I'm looking to write a function like Object.assign or _.merge, but that operates on GraphQLSchema objects.

Suppose I have two instances of GraphQLSchema, call them Base and Other, and I would like to merge Other into Base to produce a new instance Result such that

  • Fields present in exactly one of Base or Other are defined in Result by their original GraphQLFieldConfig
  • Fields present in both are reduced to the GraphQLFieldConfig in Other.

It looks as though there is no documented means to do this. Is that correct? If I went the (considerably more dangerous) undocumented route, I've noticed that I could exploit internal properties of the object:

enter image description here, but I'd prefer not to do that.

Any advice would be appreciated. Thanks in advance!

3

There are 3 best solutions below

1
On BEST ANSWER

Please check the library merge-graphql-schemas. I think this may help you

0
On

Using mergeSchemas from 'graphql-tools', you can merge GraphQLSchema objects

https://www.apollographql.com/docs/graphql-tools/schema-stitching.html#mergeSchemas

import { mergeSchemas } from 'graphql-tools';

const schema = mergeSchemas({
  schemas: [
    chirpSchema,
    authorSchema,
  ],
});
0
On

Here is my solution:

const { mergeTypes } = require('merge-graphql-schemas');
const { printSchema, parse } = require('graphql');

const typeArray = graphqlSchemas.map(printSchema);
const schema = mergeTypes(typeArray, { all: true });

  try {
    parse(schema);
  } catch (err) {
    console.log(err);
  }

graphqlSchemas is GraphQLSchema type. For my case, it's array.

printSchema convert GraphQLSchema to string template schema.

mergeTypes merge all string template schemas into one.

And, for safety, use try/catch to validate the schema is valid or not.