How to split a long GraphQL schema

前端 未结 3 1732
情深已故
情深已故 2021-02-08 07:32

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

3条回答
  •  春和景丽
    2021-02-08 08:24

    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');

提交回复
热议问题