检查缺少的解析器

check for missing resolvers

您将如何扫描架构以查找缺少查询和非标量字段的解析器?

我正在尝试使用动态架构,因此我需要能够以编程方式对此进行测试。我一直在浏览 graphql 工具几个小时以找到执行此操作的方法,但我一无所获...

感谢任何帮助!

给定一个 GraphQLSchema 实例(即 makeExecutableSchema 返回的内容)和您的 resolvers 对象,您可以自己检查一下。这样的事情应该有效:

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.`
            )
          }
        }
      }
    }
  }
}