Graphql中的包装器类型是什么?

我正在学习GraphQl官方文档。

当我进入内省 link here

一章时

我遇到了一种叫做包装器类型的东西。

输入

{
  __type(name: "Droid") {
    name
    fields {
      name
      type {
        name
        kind
      }
    }
  }
}

输出:

{
  "data": {
    "__type": {
      "name": "Droid","fields": [
        {
          "name": "id","type": {
            "name": null,# here 
            "kind": "NON_NULL"
          }
        },{
          "name": "name",{
          "name": "friends",#  here 
            "kind": "LIST"
          }
        },{
          "name": "friendsConnection",{
          "name": "appearsIn",{
          "name": "primaryFunction","type": {
            "name": "String",# normal here
            "kind": "SCALAR"
          }
        }
      ]
    }
  }
}

该文章声称类型为的那些字段的名称为NULL,因为它是类型为NON_NULL的“ wrapper”

有人可以解释什么是包装器类型吗?最好提供一个示例或代码来解释为什么 primaryFunction 具有名称,而其他人却没有。

Vicson515 回答:Graphql中的包装器类型是什么?

来自spec

  

到目前为止,所有类型均假定为可为空且为单数:标量字符串返回null或单数字符串。

     

GraphQL模式可以描述一个字段代表其他类型的列表;为此提供了列表类型,并包装了另一种类型。

     

类似地,Non-Null类型包装了另一种类型,并表示结果值永远不会为null(并且错误不会导致null值)。

     

这两种类型称为“包装类型”;非包装类型称为“命名类型”。包装类型具有基础的命名类型,可以通过连续解开该类型直到找到命名类型来找到它。

包装类型包装另一个类型,它本身也可以是包装类型。但是,当“解开”每种包装类型时,最终您必须找到与所有这些包装类型相关联的命名类型。换句话说,包装类型永远不能单独使用。包装类型始终只有一个与其关联的命名类型。

自省,要确定包装类型是包装类型,请使用ofType字段:

{
  __schema {
    types {
      name
      ofType {
        name
      }
    }
  }
}

您可以为可能的“解包”类型进一步添加其他级别:

{
  __schema {
    types {
      name
      ofType {
        name
        ofType {
          name
        }
      }
    }
  }
}

关于为什么内省并没有显示这些类型的名称,这是因为该规范特别禁止使用。看一下List类型的部分:

  

列表表示GraphQL中的值序列。列表类型是类型修饰符:它在ofType字段中包装了另一个类型实例,该实例定义了列表中每个项目的类型。

     

字段

     
      
  • 种类必须返回__TypeKind.LIST。
  •   
  • ofType:任何类型。
  •   
  • 所有其他字段必须返回null。
  •   
,

这是前几天我完成的教程中的一些片段。它代表用GraphQLNonNull运算符包装的类型(用于服务器端):

const ContestStatusType = require('./contest-status')
const NameType = require('./name')

module.exports = new GraphQLObjectType({
  name: 'ContestType',fields: {
    id: { type: GraphQLID },description: { type: GraphQLString },status: { type: new GraphQLNonNull(ContestStatusType) },createdAt: { type: new GraphQLNonNull(GraphQLString) },createdBy: { type: new GraphQLNonNull(GraphQLString) },names: {
      type: new GraphQLList(NameType),resolve(obj,args,{ loaders,pgPool }) {
        return loaders.namesForContestIds.load(obj.id);
        return pgdb(pgPool).getNames(obj)
      }
    }
  }
});
本文链接:https://www.f2er.com/3082105.html

大家都在问