Michael Darweesh
Michael Darweesh

Reputation: 3

With GraphQLSchema, is there syntax to modularlize GraphQLObjectTypes?

How do I refactor userThat (and likely several other related fields) into other nice modular files and then include them into root_query_type.js

This is a vanilla node/express/graphql GraphQLObjectType implementation.

Or am I destined to have a huge root_query_type.js ?

schema.js

module.exports = new GraphQLSchema({
  query: RootQueryType
});

root_query_type.js

const RootQueryType = new GraphQLObjectType({
  name: 'RootQueryType',
  fields: {
    userThis: {
      type: UserType,
      resolve(parentValue, args, request) {
        return thisResult;
      }
    },
    userThat: {
      type: UserType,
      args: {
        thatArgs: { type: new GraphQLNonNull(GraphQLString) },
      },
      resolve: (parentValue, arg, request) => {
        return thatResult;
      },
    },

Upvotes: 0

Views: 199

Answers (1)

Herku
Herku

Reputation: 7666

Here is what I usually do:

// user.js

const User = new GraphQLObjectType({ ... });

const queryFields = {
  userThis: {
    type: UserType,
    resolve(parentValue, args, request) {
      return thisResult;
    }
  },
};

const mutationFields = { ... };

module.exports = { User, queryFields, mutationFields };
// RootQueryType.js

// rename queryFields to userQueryFields as we might want to import queryFields
// from many different modules
const { queryFields: userQueryFields } = require('./modules/user.js');

const RootQueryType = new GraphQLObjectType({
  name: 'RootQueryType',
  fields: {
    ...userQueryFields,
  },
});

Upvotes: 1

Related Questions