Search code examples
graphqlapollo

Split the graphql resolvers file into seperatefiles


I'm working with GraphQL and have a resolvers.js file that looks like this:

const User = require("../models/User");
const Post = require("../models/Post");

module.exports = {
  Query: {
    async users(){...},
    async user(){...},
    async posts(){...},
    async post(){...},
  },
  User: {...},
  Post: {...},
  Mutation: {
    createUser(){...},
    login(){...},
    createPost(){...},
  },
}

But if I have more models, queries and mutations the file is gonna be very long. How can I split this into seperate files? One for user queries and mutations, one for posts and so. Or is that not possible? Maybe there's a way to combine this with the schema.js file? So that I can split the schema too and put schema/resolver from User into a file. I'm still a beginner in coding.


Solution

  • I found a way to do it very easy actually. In the schema.js I can use lodash merge to combine multiple resolver files and for the typedefs I just use an array. This way I can split everything into seperate files.

    const { merge } = require("lodash");
    
    module.exports = makeExecutableSchema({
      typeDefs: [typeDefs, userTypeDefs],
      resolvers: merge(resolvers, userResolvers)
    });