在graphql中嵌套数据的正确方法是什么? [英] What is the correct way to nest data within a graphql?

查看:47
本文介绍了在graphql中嵌套数据的正确方法是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在数据库中有一个地址,已将该地址放入 location 哈希中.哈希包含用于 streetAddress city state zipCode 的单独键.我已经将数据嵌套在我的graphql模式文件中:

I have an address in my database that I've put into a location hash. The hash contains separate keys for streetAddress, city, state, and zipCode. I've nested the data like so in my graphql schema file:

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

我已经实现了这样的模式类型:

And I've implemented the schema type like this:

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中进行查询时,收到一条错误消息,指出输出类型未定义:

However, I get an error message saying that the output type is undefined when I try to do a query in graphql:

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

我相信我了解错误的出处;我假设它希望 location 也具有类型.这样做/修复此错误消息的正确语法是什么?

I believe I understand where the error is coming from; I'm assuming that it expects location to have a type as well. What would be the correct syntax for doing this/fixing this error message?

推荐答案

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

As you guessed, you cannot have nested fields like that. You need to create a separate type for every object in your schema. First create the type:

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 },
  }),
})

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

or if you don't need to reuse the type, you can define it inline like this:

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 }
        }),
      })
    },
  }),
})

这篇关于在graphql中嵌套数据的正确方法是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆