检查缺少的解析器

时间:2019-05-12 00:13:58

标签: graphql graphql-js apollo-server graphql-tools

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

我正在尝试使用动态架构,因此我需要能够以编程方式进行测试。我已经花了几个小时浏览graphql工具来找到一种方法来实现此目的,但是我却一无所获...

感谢您的帮助!

1 个答案:

答案 0 :(得分:2)

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