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?
-
I wrote a library that can do this github.com/graphql-factory/graphql-factoryvbranden– vbranden2017-05-07 14:33:28 +00:00Commented May 7, 2017 at 14:33
-
Here is an article on the best way to do this if you're using Apollo's graphql-tools: hackernoon.com/…Nicolas Dao– Nicolas Dao2017-08-10 01:46:39 +00:00Commented Aug 10, 2017 at 1:46
3 Answers
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.
1 Comment
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!
Comments
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.