How to split a long GraphQL schema
Make it separate folder and structure as well to make codes maintainable I do the following:
GraphQL Example Repository
File Structure Screenshot
const express = require('express');
const glob = require("glob");
const {graphqlHTTP} = require('express-graphql');
const {makeExecutableSchema, mergeResolvers, mergeTypeDefs} = require('graphql-tools');
const app = express();
//iterate through resolvers file in the folder "graphql/folder/folder/whatever*-resolver.js"
let resolvers = glob.sync('graphql/*/*/*-resolver.js')
let registerResolvers = [];
for (const resolver of resolvers){
// add resolvers to array
registerResolvers = [...registerResolvers, require('./'+resolver),]
}
//iterate through resolvers file in the folder "graphql/folder/folder/whatever*-type.js"
let types = glob.sync('graphql/*/*/*-type.js')
let registerTypes = [];
for (const type of types){
// add types to array
registerTypes = [...registerTypes, require('./'+type),]
}
//make schema from typeDefs and Resolvers with "graphql-tool package (makeExecutableSchema)"
const schema = makeExecutableSchema({
typeDefs: mergeTypeDefs(registerTypes),//merge array types
resolvers: mergeResolvers(registerResolvers,)//merge resolver type
})
// mongodb connection if you prefer mongodb
require('./helpers/connection');
// end mongodb connection
//Make it work with express "express and express-graphql packages"
app.use('/graphql', graphqlHTTP({
schema: schema,
graphiql: true,//test your query or mutation on browser (Development Only)
}));
app.listen(4000);
console.log('Running a GraphQL API server at http://localhost:4000/graphql');
There are multiple options, here are three of them:
You can take a look at Apollo's blog - they show a way to modularize the schema: Modularizing your GraphQL schema code If you want an example, you can take a look at this github repository
Of course you can always just use the template literals to embed parts of the schema as strings:
const countryType = `
type Country {
_id: ID!
name: String!
region: [Region!]!
}
`
const regionType = `
type Region {
_id: ID!
name: String!
countries: [Country!]
}
`
const schema = `
${countryType}
${regionType}
# ... more stuff ...
`
module.exports = buildSchema(schema);
- Another way is to use the code first approach and write the schemas in javascript instead of graphql schema language.