I am trying to create a Schema, however is going to get too long and confusing, what are the best practices to split the different queries, mutations and inputs so I can just r
You could use Type definitions (SDL) merging of graphql-tools
as well.
This tools merged GraphQL type definitions and schema. It aims to merge all possible types, interfaces, enums and unions, without conflicts.
The doc introduces multiple ways to merge SDL.
I made an example of modularizing-the-schema using apollo-server
tech stack.
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);
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');