0

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

我正在尝试使用动态模式,因此我需要能够以编程方式对其进行测试。我已经浏览了几个小时的graphql工具来找到一种方法来做到这一点,但我无处可去......

任何帮助表示赞赏!

4

1 回答 1

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.`
            )
          }
        }
      }
    }
  }
}
于 2019-05-12T00:55:51.933 回答