Documentation
Essentials
Resolvers

Resolvers

Let’s focus on resolve functions usually called just resolvers.

With GraphQL-Modules, you implement your resolvers in the same way you do in any other GraphQL implementation.

Modules created by GraphQL-Modules are smart enough to detect incorrect resolvers (that don’t match type definitions or extensions for example). It helps you to detect duplicate and incorrect resolvers, or old resolvers that shouldn’t be there.

Resolvers Example

Let’s take for example the following schema for User and Query.

import { createModule, gql } from 'graphql-modules'
 
export const myModule = createModule({
  id: 'my-module',
  dirname: __dirname,
  typeDefs: gql`
    type Query {
      user(id: ID!): User
    }
 
    type User {
      id: ID!
      username: String!
    }
  `,
  resolvers: {
    Query: {
      user(root, { id }) {
        return {
          _id: id,
          username: 'jhon'
        }
      }
    },
    User: {
      id(user) {
        return user._id
      },
      username(user) {
        return user.username
      }
    }
  }
})

Dynamically Load Resolvers Files

If you have many resolvers files in your module, and you wish to load it dynamically, you can use loaders from @graphql-tools/load-files!

Start by installing this package:

npm i @graphql-tools/load-files

Next, use it to load your files dynamically:

import MyQueryType from './query.type.graphql'
import { createModule } from 'graphql-modules'
import { loadFilesSync } from '@graphql-tools/load-files'
import { join } from 'path'
 
export const myModule = createModule({
  id: 'my-module',
  dirname: __dirname,
  typeDefs: loadFilesSync(join(__dirname, './typeDefs/*.graphql')),
  resolvers: loadFilesSync(join(__dirname, './resolvers/*.ts'))
})