GraphQL - 从嵌套的 JSON 对象中获取所有字段 [英] GraphQL - Get all fields from nested JSON object

查看:65
本文介绍了GraphQL - 从嵌套的 JSON 对象中获取所有字段的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

零到 GraphQL in 30 中所述,我正在将 GraphQL 包装器放在现有的 REST API 上分钟.我有一个产品的 API 端点,它有一个指向嵌套对象的属性:

I'm putting a GraphQL wrapper over an exiting REST API as described in Zero to GraphQL in 30 minutes. I've got an API endpoint for a product with one property that points to a nested object:

// API Response
{
  entity_id: 1,
  nested_object: {
    key1: val1,
    key2: val2,
    ...
  }
}

是否可以定义架构,以便我可以在不显式定义嵌​​套对象及其所有属性的情况下获取整个嵌套对象?我希望我的查询只指定我想要嵌套对象,而不需要从嵌套对象中指定我想要的所有属性:

Is it possible to define the schema so that I can get this entire nested object without explicitly defining the nested object and all of its properties? I want my query to just specify that I want the nested object, and not need to specify all the properties I want from the nested object:

// What I want
{
  product(id: "1") {
    entityId
    nestedObject
  }
}

// What I don't want
{
  product(id: "1") {
    entityId
    nestedObject {
      key1
      key2
      ...
    }
  }
}

我可以做第二个版本,但它需要很多额外的代码,包括创建一个 NestedObjectType 并指定所有嵌套的属性.我还想出了如何自动获取所有键的列表,如下所示:

I can do the second version, but it requires lots of extra code, including creating a NestedObjectType and specifying all the nested properties. I've also figured out how to automatically get a list of all the keys, like so:

const ProductType = new GraphQLObjectType({
  ...

  fields: () => ({
    nestedObject: {
      type: new GraphQLList(GraphQLString),
      resolve: product => Object.keys(product.nested_object)
    }
  })
})

不过,我还没有找到自动返回整个对象的方法.

I haven't figured out a way to automatically return the entire object, though.

推荐答案

我可以做第二个版本,但它需要很多额外的代码,包括创建一个 NestedObjectType 和指定所有嵌套的属性.

I can do the second version, but it requires lots of extra code, including creating a NestedObjectType and specifying all the nested properties.

去做吧!这将会非常棒.为了充分发挥 GraphQL 的潜力,这就是要走的路.

Do it! It will be great. That's the way to go in order to use GraphQL to its full potential.

除了防止过度获取之外,它还为您提供了许多其他好处,例如类型验证,以及更具可读性和可维护性的代码,因为您的架构提供了更完整的数据描述.稍后您会感谢自己预先做了额外的工作.

Aside from preventing over-fetching, it also gives you a lot of other benefits like type validation, and more readable and maintainable code since your schema gives a fuller description of your data. You'll thank yourself later for doing the extra work up front.

如果由于某种原因你真的不想走那条路并完全理解后果,你可以使用 JSON.stringify 将嵌套对象编码为字符串.

If for some reason you really don't want to go that route though and fully understand the consequences, you could encode the nested objects as strings using JSON.stringify.

但就像我说的,我建议你不要!

But like I said, I recommend you don't!

这篇关于GraphQL - 从嵌套的 JSON 对象中获取所有字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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