Ryan
Ryan

Reputation: 7959

How to modularize GraphQL schema when using `buildSchema`?

It has been about a year since I updated my graphql-js dependency. I see now that there is a utility that simplifies schema generation: buildSchema. This function takes, as an arg, your entire schema, as a string, in the GraphQL language. That's awesome, but is there a way to modularize this? My schema is not super small, and would suck to cram into a single .graphql file. Is there some sort of utility or pattern for storing each type definition in its own file, for example?

Upvotes: 6

Views: 3965

Answers (3)

Nicolas Dao
Nicolas Dao

Reputation: 1097

If you're using Apollo's graphql-tools, then I've found that the best way to structure your schema is to use schemaglue.js (disclaimer: I've built this):

const { makeExecutableSchema } = require('graphql-tools')
const { glue } = require('schemaglue')

const { schema, resolver } = glue('src/graphql')

const executableSchema = makeExecutableSchema({
    typeDefs: schema,
    resolvers: resolver
})

And then you'll be able to structure your schema and resolvers with something similar to this:

- src/
   |__ graphql/
          |__ product/
          |       |__ schema.js
          |       |__ resolver.js
          |
          |__ variant/
                  |__ schema.js
                  |__ resolver.js

- index.js
- package.json

I've written a detailed article about this here.

Upvotes: 0

Tom
Tom

Reputation: 61

You can further improve your schema modularity by using merge-graphql-schemas package.

Here is a modular graphql server seed - graphql-server-seed

The project structure allows you to separate your types and resolver to multiple files. Hope it helps!

Upvotes: 0

mstorkson
mstorkson

Reputation: 1260

If you have the graphql-tools package, you can use makeExecutableSchema to modularize your schema like so:

const schema = makeExecutableSchema({
    typeDefs: [schema1, schema2, schema3, ...],
    resolvers: resolvers,
});

That way each type can be defined in its own file.

Upvotes: 5

Related Questions