check for missing resolvers

Asked by At

How would you scan schema for missing resolver for queries and non-scalar fields ?

I'm trying to work with a dynamic schema so I need to be able to test this programmatically. I've been browsing graphql tools for few hours to find a way to do this, but I'm getting nowhere...

any help is appreciated !

1 Answers

2
Daniel Rearden On Best Solutions

Given an instance of GraphQLSchema (i.e. what's returned by makeExecutableSchema) and your resolvers object, you can just check it yourself. Something like this should work:

const { isObjectType, isWrappingType, isLeafType } = require('graphql')

assertAllResolversDefined (schema, resolvers) {
  // Loop through all the types in the schema
  const typeMap = schema.getTypeMap()
  for (const typeName in typeMap) {
    const type = schema.getType(typeName)
    // We only care about ObjectTypes
    // Note: this will include Query, Mutation and Subscription
    if (isObjectType(type) && !typeName.startsWith('__')) {
      // Now loop through all the fields in the object
      const fieldMap = type.getFields()
      for (const fieldName in fieldMap) {
        const field = fieldMap[fieldName]
        let fieldType = field.type

        // "Unwrap" the type in case it's a list or non-null
        while (isWrappingType(fieldType)) {
          fieldType = fieldType.ofType
        }

        // Only check fields that don't return scalars or enums
        // If you want to check *only* non-scalars, use isScalarType
        if (!isLeafType(fieldType)) {
          if (!resolvers[typeName]) {
            throw new Error(
              `Type ${typeName} in schema but not in resolvers map.`
            )
          }
          if (!resolvers[typeName][fieldName]) {
            throw new Error(
              `Field ${fieldName} of type ${typeName} in schema but not in resolvers map.`
            )
          }
        }
      }
    }
  }
}