简体   繁体   English

如何在 GraphQL 中将复杂的 object 作为标量类型返回?

[英]How to return complex object as scalar type in GraphQL?

Let's imagine we have GraphQL API that can return an object Entity with Id and Name properties and I requested Name only:假设我们有 GraphQL API 可以返回一个 object实体,它具有IdName属性并且我只请求了Name

query {
    entities {
        name
    }
}

And it returns它返回

{
    "data": {
        "entities": [
        {
            "name": "Name1"
        },
        {
            "name": "Name2"
        }
        ]
    }
}

But what if I want to have only the name of entities as a scalar type?但是,如果我只想将实体名称作为标量类型呢? In other words, I want to have something like:换句话说,我想要类似的东西:

{
    "data": {
        "entities": [
            "Name1",
            "Name2"
        ]
    }
}

Is it possible to have such result without changes on the GraphQL API side?是否有可能在 GraphQL API 端不进行更改的情况下获得这样的结果? Aliases, Fragments, etc. GraphQL has a lot of built-in query capabilities, but none of the known me can return complex objects as scalar type.别名、片段等 GraphQL 有很多内置的查询能力,但是没有一个知道我可以将复杂对象作为标量类型返回。

what you're asking for is almost impossible if you don't want to change the type definition for Entities .如果您不想更改Entities的类型定义,那么您所要求的几乎是不可能的。

This:这个:

Entity: id: int! name: String
entities(): [Entity]

returns an array of objects with keys name and id .返回具有键nameid的对象数组。

To achieve what you're asking you either change Entity to be just a string or have your client reduce that object to an array of just Entity names when they receive it.为了实现您的要求,您可以将Entity更改为只是一个字符串,或者让您的客户在收到 object 时将其减少为仅包含Entity names的数组。

They could do something like this:他们可以这样做:

 const data = { entities: [ { name: 'Name1', }, { name: 'Name2', }, ], }; const entityNames = data.entities.reduce( (acc, curr) => [...acc, curr.name], [] ); console.log(entityNames);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM