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

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

问题描述

我正在将GraphQL包装器放在退出的REST API上,如将GraphQL归零到30中所述分钟.我有一个产品的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天全站免登陆