Apollo-server: Merging multiple ASTs from gql tag in v2

Created on 5 Jul 2018  路  6Comments  路  Source: apollographql/apollo-server

Is there a way to merge multiple types wrapped in gql so they can be passed to ApolloServer? What I am envisioning is

const hello = gql`Query { hello: String }`
const hi = gql`Query { hi: String }`

const typeDefs = mergeTypes([hello, hi])
new ApolloServer({ typeDefs, resolvers: ... })

// or yet better

new ApolloServer({ typeDefs: [hello, hi], resolvers: ... })

It seems resolvers already accepts an object or an _array_ of resolver objects (which is great!). But if you pass an array to typeDefs you'd get Error: Type "Query" was defined more than once. It seems it only supports a String inside gql tag so far. It works though if you default back to makeExecutableSchema from v1, but then you must sacrifice syntax highlighting and get rid of gql wrapper.

Any way to make this work in v2?

Thanks!

Most helpful comment

I had the same problem, and was able to do it using mergeTypes from https://www.npmjs.com/package/merge-graphql-schemas#merging-type-definitions. Note, mergeTypes is capable of merging an array of DocumentNodes (the output of gql). However, it returns an SDL string, so you will need to send that back through gql. So it'll look something like this:

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

const hello = gql`Query { hello: String }`
const hi = gql`Query { hi: String }`

const typeDefs = gql`${mergeTypes([hello, hi])}`;

All 6 comments

Sure, you'll be able to use something like:

const hello = gql`type Query { hello: String }`
const hi = gql`extends type Query { hi: String }`

const typeDefs = mergeTypes([hello, hi])
new ApolloServer({ typeDefs, resolvers: ... })

// or yet better

new ApolloServer({ typeDefs: [hello, hi], resolvers: ... })

https://blog.apollographql.com/modularizing-your-graphql-schema-code-d7f71d5ed5f2 is a good example

Phenomenal! Thanks for the link; the post explains it very well. My last wish is that this gets documented...

hey, sorry, but @evans where is that mergeTypes function coming from? I can't find that anywhere in the API or other related libraries.

@jeffwhelpley It was just example code that I was thinking of. mergeTypes doesn't exist, but @evans was pointing to the extends keyword for extending types.

extends should be extend in the example. @evans

I had the same problem, and was able to do it using mergeTypes from https://www.npmjs.com/package/merge-graphql-schemas#merging-type-definitions. Note, mergeTypes is capable of merging an array of DocumentNodes (the output of gql). However, it returns an SDL string, so you will need to send that back through gql. So it'll look something like this:

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

const hello = gql`Query { hello: String }`
const hi = gql`Query { hi: String }`

const typeDefs = gql`${mergeTypes([hello, hi])}`;
Was this page helpful?
0 / 5 - 0 ratings