【问题标题】:What is the correct way to nest data within a graphql?在graphql中嵌套数据的正确方法是什么?
【发布时间】:2020-06-14 07:30:18
【问题描述】:

我的数据库中有一个地址,我已将其放入location 哈希中。哈希包含 streetAddresscitystatezipCode 的单独键。我已经在我的 graphql 模式文件中嵌套了这样的数据:

location: {
    streetAddress: { 
      type: String,
      required: true,
      unqiue: true
    },
    city: {
      type: String,
      required: true
    }, 
    state: {
      type: String,
      required: true
    },
    zipCode: {
      type: Number,
      required: true
    }
  }

我已经实现了这样的架构类型:

fields: () => ({
    id: { type: GraphQLID },
    name: { type: GraphQLString },
    id: {type: GraphQLID},
    phoneNum: { type: GraphQLString },
    location: {
      streetAddress: { type: GraphQLString },
      city: { type: GraphQLString },
      state: { type: GraphQLString },
      zipCode: { type: GraphQLInt }
    }
    ...

但是,当我尝试在 graphql 中进行查询时,我收到一条错误消息,指出输出类型未定义:

"message": "The type of RestaurantType.location must be Output Type but got: undefined."

我相信我了解错误的来源;我假设它期望location 也有一个类型。执行此操作/修复此错误消息的正确语法是什么?

【问题讨论】:

    标签: graphql


    【解决方案1】:

    如您所料,您不能有这样的嵌套字段。您需要为架构中的每个对象创建一个单独的类型。首先创建类型:

    const Location = new GraphQLObjectType({
      name: 'Location',
      fields: () => ({
        streetAddress: { type: GraphQLString },
        city: { type: GraphQLString },
        state: { type: GraphQLString },
        zipCode: { type: GraphQLInt }
      }),
    })
    

    然后使用它:

    const Restaurant = new GraphQLObjectType({
      name: 'Restaurant',
      fields: () => ({
        id: { type: GraphQLID },
        name: { type: GraphQLString },
        location: { type: Location },
      }),
    })
    

    或者如果你不需要重用类型,你可以像这样内联定义它:

    const Restaurant = new GraphQLObjectType({
      name: 'Restaurant',
      fields: () => ({
        id: { type: GraphQLID },
        name: { type: GraphQLString },
        location: {
          type: new GraphQLObjectType({
            name: 'Location',
            fields: () => ({
              streetAddress: { type: GraphQLString },
              city: { type: GraphQLString },
              state: { type: GraphQLString },
              zipCode: { type: GraphQLInt }
            }),
          })
        },
      }),
    })
    

    【讨论】:

    • 好吧,所以没有嵌套字段。所以从你的例子来看,看起来我仍然可以将位置数据分解成一个单独的常量,对吗?为了组织起见,这是有道理的。
    • 是的,如果你想内联它而不是你想的话,只要你不需要在别处重用该类型。有关示例,请参见编辑后的答案。
    • 啊好吧,这太棒了!感谢您的澄清!
    猜你喜欢
    • 1970-01-01
    • 2012-08-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-11-10
    • 2017-03-04
    相关资源
    最近更新 更多