【问题标题】:check for missing resolvers检查缺少的解析器
【发布时间】:2019-09-29 09:41:26
【问题描述】:

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

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

感谢任何帮助!

【问题讨论】:

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


    【解决方案1】:

    给定一个 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.`
                )
              }
            }
          }
        }
      }
    }
    

    【讨论】:

    • 我修复了丢失的逻辑,但除此之外,它工作得很好!我不知道这些花哨的方法(isObjectType、isWrappingType、isLeafType)。文档不是很好...谢谢!
    猜你喜欢
    • 2019-03-23
    • 2018-11-06
    • 2017-03-31
    • 2016-07-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-06-14
    相关资源
    最近更新 更多